SQL Server - Invalid column name - sql-server

Please help, I have a problematic query to display the column OrderNo2.
the following is the query:
SELECT
V.id, V.TypeApv, V.CreateDate,
P.Requestor, VE.VendorName, V.InvoiceNo, V.Hawb,
PA.PaymentFor, V.Amount, V.Curr, V.DueDate, V.Remarks, V.OrderNo,
(SELECT
STUFF((SELECT DISTINCT ', ' + CASE WHEN [e-SAM Case]='Subsequent' OR [e-SAM Case]='DDT' AND [Local SAP PO] LIKE '5%' OR [e-SAM Case]='FBS 4'
THEN PoNo ELSE [Local SAP PO] END
FROM v_copo VC
WHERE VC.AWB1 = V.Hawb
FOR XML PATH('')), 1, 1, '')) AS OrderNo2,
(SELECT ISNULL(OrderNo2, V.OrderNo)) AS OrderNoFinal
FROM
APV_AF V
LEFT JOIN
APV_Person P ON P.id = V.Requestor
LEFT JOIN
APV_Vendor VE ON VE.IDVendor = V.VendorName
LEFT JOIN
APV_Payment PA ON PA.IDPayment = V.PaymentFor
ORDER BY
V.CreateDate DESC

You cannot reference an alias in the same scope where it was defined (apart from the order by clause). Typical work arounds include a subquery or CTE.
In SQL Server though, a simple option is a lateral join:
SELECT
V.id, V.TypeApv, V.CreateDate,
P.Requestor, VE.VendorName, V.InvoiceNo, V.Hawb,
PA.PaymentFor, V.Amount, V.Curr, V.DueDate, V.Remarks, V.OrderNo,
X.OrderNo2,
ISNULL(X.OrderNo2, V.OrderNo) AS OrderNoFinal
FROM APV_AF V
LEFT JOIN APV_Person P ON P.id = V.Requestor
LEFT JOIN APV_Vendor VE ON VE.IDVendor = V.VendorName
LEFT JOIN APV_Payment PA ON PA.IDPayment = V.PaymentFor
OUTER APPLY (
SELECT
STUFF((SELECT DISTINCT ', ' + CASE WHEN [e-SAM Case]='Subsequent' OR [e-SAM Case]='DDT' AND [Local SAP PO] LIKE '5%' OR [e-SAM Case]='FBS 4'
THEN PoNo ELSE [Local SAP PO] END
FROM v_copo VC
WHERE VC.AWB1 = V.Hawb
FOR XML PATH('')), 1, 1, '') AS OrderNo2
) X
ORDER BY V.CreateDate DESC

Related

how to concatenate text from multiable rows in SSRS?

I got introduced to SSRS recently and I am facing a problem in extracting data from the database.
I searched online and I found out that this is called concatenate text from multiable rows. Now, I tried a code.. but in the results, it give me the data duplicated next to each other separated by a comma. Now I am happy that it is separating the result with a coma... but why giving me the data duplicated?
The Code:
select distinct wm1.Date, p1.[Medical Record Number], Wound_Type =CONCAT
((
select distinct CAST(wt2.Name as VARCHAR(MAX))+ ' /// ' from dbo.[Wound Type] as wt2
inner join dbo.[Wound Management] as wm2 on wm2.[Wound Type_ID] = wt2.ID
inner join dbo.Patient as p2 on wm2.[Owner (Patient)_Patient_ID]=p2.ID
where wm1.Date=wm2.Date
FOR XML PATH('')
),wt1.Name)
from dbo.[Wound Type] as wt1
inner join dbo.[Wound Management] as wm1 on wm1.[Wound Type_ID] = wt1.ID
inner join dbo.Patient as p1 on wm1.[Owner (Patient)_Patient_ID]=p1.ID
group by wm1.Date, wt1.Name, p1.[Medical Record Number]
the result:
Please Help.
Your data is duplicated because you are CONCATing the list of wt2.Names with the wt1.Name - ,wt1.Name). The one with NULL date isn't finding a matching record and is only showing the wt1.Name
Actually I think you may want to use the STUFF function instead of CONCAT to remove any extra slashes at the end.
SELECT DISTINCT wm1.Date, p1.[Medical Record Number], Wound_Type = STUFF(
(
SELECT DISTINCT ' /// ' + CAST(wt2.Name as VARCHAR(MAX))
from dbo.[Wound Type] as wt2
inner join dbo.[Wound Management] as wm2 on wm2.[Wound Type_ID] = wt2.ID
inner join dbo.Patient as p2 on wm2.[Owner (Patient)_Patient_ID]=p2.ID
where wm1.Date=wm2.Date
FOR XML PATH('')
), 1, 5, '' )
from dbo.[Wound Type] as wt1
inner join dbo.[Wound Management] as wm1 on wm1.[Wound Type_ID] = wt1.ID
inner join dbo.Patient as p1 on wm1.[Owner (Patient)_Patient_ID]=p1.ID
group by wm1.Date, wt1.Name, p1.[Medical Record Number]
This doesn't fix that NULL date issue. You could wrap the STUFF in an ISNULL.
SELECT DISTINCT wm1.Date, p1.[Medical Record Number], Wound_Type = ISNULL(STUFF(
(
SELECT DISTINCT ' /// ' + CAST(wt2.Name as VARCHAR(MAX))
from dbo.[Wound Type] as wt2
inner join dbo.[Wound Management] as wm2 on wm2.[Wound Type_ID] = wt2.ID
inner join dbo.Patient as p2 on wm2.[Owner (Patient)_Patient_ID]=p2.ID
where wm1.Date=wm2.Date
FOR XML PATH('')
), 1, 5, '' )
, wt1.Name)
from dbo.[Wound Type] as wt1
inner join dbo.[Wound Management] as wm1 on wm1.[Wound Type_ID] = wt1.ID
inner join dbo.Patient as p1 on wm1.[Owner (Patient)_Patient_ID]=p1.ID
group by wm1.Date, wt1.Name, p1.[Medical Record Number]
Here's an explanation of stuff:
How Stuff and 'For Xml Path' work in SQL Server?

Stuff function for multiple columns in SQL Server

I have some queries to stuff a specific column.
Query 1:
with cte as
(
select distinct
w.Work_WorkID, k.Name as "Secretariat_Attendees"
from
d, m, s, w, a, k
where
d.DataID = m.Map_MapObjID
and m.Map_MapID = s.SubWork_MapID
and s.SubWork_WorkID = w.Work_WorkID
and w.Work_WorkID = a.WF_ID
and d.DataID = 35269818
and a.WF_AttrID = 17
and k.ID = a.WF_ValInt
)
select distinct
t2.Work_WorkID,
stuff((select N' ; ' + Secretariat_Attendees
from (select Work_WorkID, Secretariat_Attendees
from cte t1
where t1.Work_WorkID = t2.Work_WorkID) AS t
for xml path('')), 1, 2, '') + N'' Secretariat_Attendees
from cte t2;
Query 1 output:
Work_WorkID Secretariat_Attendees
----------------------------------------------------
35273587 Admin CEO Office ; BD_TestUser ; Diana
35277687 10023165 ; 10036755 ; 10075193
Query 2:
with cte as (
select Distinct w.Work_WorkID,k.Name as "Committee_Attendees" from d, m, s, w, a, k
where d.DataID=m.Map_MapObjID and m.Map_MapID=s.SubWork_MapID and s.SubWork_WorkID=w.Work_WorkID
and w.Work_WorkID=a.WF_ID and d.DataID=35269818 and a.WF_AttrID=5 and k.ID=a.WF_ValInt
)
select distinct t2.Work_WorkID,
stuff((select N' ; ' + Committee_Attendees
from (select Work_WorkID, Committee_Attendees
from cte t1 where t1.Work_WorkID = t2.Work_WorkID) AS t
for xml path('')
), 1, 2, '') + N'' Committee_Attendees from cte t2;
Query 2 Output:
Work_WorkID Committee_Attendees
35273587 Deva ; User 1
35277687 User3 ; User 4
How do I combine both these query into one to get the below desired output based on Work_WorkID?
Work_WorkID Secretariat_Attendees Committee_Attendees
35273587 Admin CEO Office ; BD_TestUser ; Diana Deva ; User 1
35277687 10023165 ; 10036755 ; 10075193 User3 ; User 4
The only difference between the two queries looks like WF_AttrID column. I moved this predicate to the sub queries. you can try this. And I also changed your table joins syntax to JOIN
with cte as
(
select distinct
w.Work_WorkID, k.Name as "Attendees", a.WF_AttrID
from
DTree d
INNER JOIN WMap m ON d.DataID = m.Map_MapObjID
INNER JOIN WSubWork s ON m.Map_MapID = s.SubWork_MapID
INNER JOIN WWork w ON s.SubWork_WorkID = w.Work_WorkID
INNER JOIN WFAttrData a ON w.Work_WorkID = a.WF_ID
INNER JOIN KUAF k ON k.ID = a.WF_ValInt
where
d.DataID = 35269818
and a.WF_AttrID IN( 5 ,17 )
)
select distinct
t2.Work_WorkID,
stuff((select N' ; ' + Secretariat_Attendees
from (select Work_WorkID, t1.Attendees AS Secretariat_Attendees
from cte t1
where t1.Work_WorkID = t2.Work_WorkID AND t1.WF_AttrID = 17) AS t
for xml path('')), 1, 2, '') + N'' Secretariat_Attendees,
stuff((select N' ; ' + Committee_Attendees
from (select Work_WorkID, t1.Attendees AS Committee_Attendees
from cte t1 where t1.Work_WorkID = t2.Work_WorkID AND t1.WF_AttrID = 5) AS t
for xml path('')
), 1, 2, '') + N'' Committee_Attendees
from cte t2;
This seems to be a simple join. If your difficulty stems from combining them into a single query, all you have to do is replace the second query's cte name to cte2, put the ctes together in the beginning, and use both queries as derived tables:
with cte as(
....first query cte....
)
,cte2 as(
....second query cte
)
select *
from
(
....query 1.....
)t1
inner join
(
......query 2 but "cte2" instead of "cte"....
)t2 on t1.Work_WorkID=t2.Work_WorkID
This is a fast, unoptimized answer. I get the feeling the ctes and the queries have common, optimizable parts. Also, please stop using the onld join notation (from table1,table2,table3.....) and start using join, you can find reasons all over the internet.

how to add subjects in same days column not multiple

I have the records below. I want to show subjects when Monday in column all subjects appear on Monday with start time and end time. How do I do this?
SELECT t.teacher_name, tci.class_name, tsb.Subject_Name, tdn.DaysName,
tss.subject_start, tss.subject_end
FROM tblsubjectSchedule tss
INNER JOIN tblsubjects tsb ON tss.subject_id = tsb.Idx
INNER JOIN tblclassinfo tci ON tss.class_id = tci.Idx
INNER JOIN tbldaysnames tdn ON tss.days_id = tdn.Idx
INNER JOIN tblteacher t ON tss.techer_id = t.Idx
WHERE tss.class_id = 2 AND t.school_id = 1
Your attachment is not completely clear. Are you going to ignore teacher_name on result?
In your screenshot you haven't included 'samad teacheer' on Monday results. You want the query only for Monday date?
If you only focus on class and days and date, I got below. please refer the attachment.Let me know if it works for you and accept my answer.
SELECT t1.class_name,t1.daysname,
subject_name =REPLACE( (SELECT (subject_name+'-start:'+CONVERT(VARCHAR, subject_start, 120)+'-End:'+CONVERT(VARCHAR, subject_end, 120)) AS [data()]
FROM [practice].[dbo].[test] t2
WHERE t2.daysname = t1.daysname
ORDER BY subject_name
FOR XML PATH('')
), ' ', ';')
FROM [practice].[dbo].[test] t1
GROUP BY daysname,class_name ;
You could also add teacher name to the schedule column: see the attachment
SELECT t1.class_name,t1.daysname,
schedule =REPLACE( (SELECT (teacher_name+'-'+subject_name+'-start:'+CONVERT(VARCHAR, subject_start, 120)+'-End:'+CONVERT(VARCHAR, subject_end, 120)) AS [data()]
FROM [practice].[dbo].[test] t2
WHERE t2.daysname = t1.daysname
ORDER BY subject_name
FOR XML PATH('')
), ' ', ';')
FROM [practice].[dbo].[test] t1
GROUP BY daysname,class_name ;
Here is the query only for the 'Monday'
SELECT t1.class_name,t1.daysname,
schedule =REPLACE( (SELECT (teacher_name+'-'+subject_name+'-start:'+CONVERT(VARCHAR, subject_start, 120)+'-End:'+CONVERT(VARCHAR, subject_end, 120)) AS [data()]
FROM [practice].[dbo].[test] t2
WHERE t2.daysname = t1.daysname
ORDER BY subject_name
FOR XML PATH('')
), ' ', ';')
FROM [practice].[dbo].[test] t1 where daysname='Monday'
GROUP BY daysname,class_name ;

SQL Pivot dynamic query error

I tried to convert rows values into columns...Below is my query...
Select * from (SELECT *
FROM ( SELECT PROJ.PROJ_ID,
PROJ.PROJ_NM AS [Project Name],
PROJ.PROJ_DS AS [Project Description],
convert(varchar(10), PROJ.PROJ_ACTL_LNCH_DT, 110) [Actual Completed Date],
PROJ.PROJ_SMRY_DS AS [Project Summary],
dbo.udf_BankContacts(PROJ.PROJ_ID) AS [BankContact],
convert(varchar(10), PROJ.PROJ_EST_LNCH_DT, 110) AS [Estimated Launch Date],
PROJ.ENTER_DT AS [Begin Date],
PROJ_STA.PROJ_STA_DS AS [Project Status],
SFTW_DEV_MTHD.SFTW_DEV_MTHD_NM AS [Software Development Method],
PROJ_PHASE.PROJ_PHASE_DS AS [Phase],
PROJ_CTGY.PROJ_CTGY_DS AS [Project Category],
(CASE WHEN PROJ.ARCH_IN='0' THEN 'N' ELSE 'C' END) AS [Archive],
PROJ.PHASE_CMNT_TX AS [Phase Comment],
PROD_TYPE_DS
FROM dbo.Project PROJ
left join dbo.PROJ_PROD PP on PROJ.PROJ_ID = PP.PROJ_ID
left join dbo.PROD_TYPE PT on PP.PROD_TYPE_ID = PT.PROD_TYPE_ID
LEFT JOIN DBO.PROJ_STA ON PROJ.PROJ_STA_ID = PROJ_STA.PROJ_STA_ID
left join dbo.SFTW_DEV_MTHD on PROJ.SFTW_DEV_MTHD_ID = SFTW_DEV_MTHD.SFTW_DEV_MTHD_ID
left join dbo.PROJ_PHASE on PROJ.PROJ_PHASE_ID = PROJ_PHASE.PROJ_PHASE_ID
left join dbo.PROJ_CTGY on PROJ.PROJ_CTGY_ID = PROJ_CTGY.PROJ_CTGY_ID
) data
PIVOT
( MAX(PROD_TYPE_DS)
FOR PROD_TYPE_DS IN ([PT1],[PT2])
) pvt2
where PROJ_ID is not null) AS ProdType
LEFT JOIN (SELECT *
FROM
(
select PROJ_ID,
PROJ_APRV_TYPE_DS = case
when col ='PROJ_APRV_TYPE_DS'
then PROJ_APRV_TYPE_DS
else PROJ_APRV_TYPE_DS+col end,
value
from
(
SELECT PROJ.PROJ_ID,
PAT.PROJ_APRV_TYPE_DS PROJ_APRV_TYPE_DS,
convert(varchar(10), PATS.APRV_EXPT_BY_DT, 120) APRV_EXPT_BY_DT,
convert(varchar(10), PATS.APRV_CMPL_DT, 120) APRV_CMPL_DT
FROM dbo.Project PROJ
left join [dbo].[PROJ_APRV_TYPE_STA] PATS
on PROJ.PROJ_ID = PATS.PROJ_ID
left join [dbo].[PROJ_APRV_STA] PAS
on PATS.PROJ_APRV_STA_ID = PAS.PROJ_APRV_STA_ID
right outer join dbo.PROJ_APRV_TYPE PAT
on PATS.PROJ_APRV_TYPE_ID = PAT.PROJ_APRV_TYPE_ID
) s
cross apply
(
select 'PROJ_APRV_TYPE_DS', PROJ_APRV_TYPE_DS union all
select ' Expected Date', APRV_EXPT_BY_DT union all
select ' Completed Date', APRV_CMPL_DT
) c (col, value)
) data
PIVOT
(
MAX(value)
FOR PROJ_APRV_TYPE_DS IN ([RMC Approval],[RMC Approval Expected Date],[RMC Approval Completed Date],[BOD Approval],[BOD Approval Expected Date],[BOD Approval Completed Date])
) pvt1 where PROJ_ID is not null ) AS Approval ON ProdType.PROJ_ID = Approval.PROJ_ID
LEFT JOIN (SELECT *
FROM ( SELECT PROJ.PROJ_ID,
ORG_SHRT_NM
FROM dbo.Project PROJ
left join dbo.PROJ_LGL_ENT_IMPCT PLEI on PROJ.PROJ_ID = PLEI.PROJ_ID
right outer join dbo.LGL_ENT LE on PLEI.LGL_ENT_ID = LE.LGL_ENT_ID
) data
PIVOT
( MAX(ORG_SHRT_NM)
FOR ORG_SHRT_NM IN ([AECB],[FSB],[TRS])
) pvt3
where PROJ_ID is not null) AS LegalEntity ON ProdType.PROJ_ID = LegalEntity.PROJ_ID LEFT JOIN
(;with cte as
(
SELECT PCGU.PROJ_ID,
name = u.USER_LST_NM + ', '+ u.USER_FIRST_NM,
CTC_GRP_DS
FROM dbo.[user] u
left join dbo.PROJ_CTC_GRP_USER PCGU
on u.USER_ID = PCGU.USER_ID
left join dbo.CTC_GRP CG
on PCGU.CTC_GRP_ID = CG.CTC_GRP_ID
)
select *
from
(
select c1.proj_id,
c1.CTC_GRP_DS,
STUFF(
(SELECT ', ' + c2.name
FROM cte c2
where c1.proj_id = c2.proj_id
and c1.CTC_GRP_DS = c2.CTC_GRP_DS
FOR XML PATH (''))
, 1, 1, '') AS name
from cte c1
) d
pivot
(
max(name)
for CTC_GRP_DS in ([Bank Contact],[Dept2])
) piv
where PROJ_ID is not null)
AS Dept ON ProdType.PROJ_ID = Dept.PROJ_ID
I am getting error
Msg 102, Level 15, State 1, Line 84
Incorrect syntax near ';'.
Msg 102, Level 15, State 1, Line 115
Incorrect syntax near ')'.
I am totally confused what i am missing it. I recently started pivot & dynamic query concepts...Please guide on it...
Your error is here.
(;with cte as
(
SELECT PCGU.PROJ_ID,
name = u.USER_LST_NM + ', '+ u.USER_FIRST_NM,
CTC_GRP_DS
FROM dbo.[user] u
left join dbo.PROJ_CTC_GRP_USER PCGU
on u.USER_ID = PCGU.USER_ID
left join dbo.CTC_GRP CG
on PCGU.CTC_GRP_ID = CG.CTC_GRP_ID
)
select *
from
(
select c1.proj_id,
c1.CTC_GRP_DS,
STUFF(
(SELECT ', ' + c2.name
FROM cte c2
where c1.proj_id = c2.proj_id
and c1.CTC_GRP_DS = c2.CTC_GRP_DS
FOR XML PATH (''))
, 1, 1, '') AS name
from cte c1
) d
You cannot have a CTE in sub selects like that.
You could try to put the CTE at the very top, or create a temp table for the select.
The error is with your CTE. You can't stick a CTE inside a query like that
(;with cte as

How can i link a sql server job name

to the SSRS report server process that uses it? the name looks like a guid, but i need to find the reporting services reports that use it.
thanks very much
Here's a query I blogged about a while back that does the join:
;WITH cte (job_id, job_name, execution_time, execution_order)
AS
(
SELECT DISTINCT j.job_id
,j.name
,CONVERT(datetime, STUFF(STUFF(run_date,7,0,'/'),5,0,'/')
+ SPACE(1)
+ STUFF(STUFF(RIGHT('000000' + CONVERT(varchar(20), run_time), 6),5,0,':'),3,0,':'))
,ROW_NUMBER() OVER (PARTITION BY j.job_id ORDER BY CONVERT(datetime, STUFF(STUFF(run_date,7,0,'/'),5,0,'/')
+ SPACE(1)
+ STUFF(STUFF(RIGHT('000000' + CONVERT(varchar(20), run_time), 6),5,0,':'),3,0,':')) DESC)
FROM msdb.dbo.sysjobs j
INNER JOIN msdb.dbo.syscategories c ON j.category_id = c.category_id
LEFT OUTER JOIN msdb.dbo.sysjobhistory jh ON j.job_id = jh.job_id
WHERE c.name ='Report Server'
)
SELECT
x.job_name
,c.name
,x.execution_time
,c.path
,su.description
,CONVERT(varchar(max), su.ExtensionSettings) as ExtensionSettings
,'EXEC msdb..sp_start_job ''' + x.job_name + '''' as SQLStatement
FROM cte x
INNER JOIN dbo.Schedule sc ON x.job_name = CONVERT(varchar(100), sc.ScheduleID)
INNER JOIN dbo.ReportSchedule rs ON sc.ScheduleID = rs.ScheduleID
INNER JOIN dbo.Subscriptions su ON rs.SubscriptionID = su.SubscriptionID
INNER JOIN dbo.Catalog c ON su.Report_OID = c.ItemID
WHERE execution_order = 1
ORDER BY 3, 2
There doesn't appear to be a straightforward method to find this out.
The following query lists the subscription IDs and the reports to which they link
select s.SubscriptionID, c.Path
from ReportServer.dbo.Subscriptions as s
JOIN ReportServer.dbo.Catalog as c
on ItemID = Report_OID
The subscription ID is then referenced inside the job step, in the following format.
exec ReportServer.dbo.AddEvent #EventType='TimedSubscription', #EventData='~subscriptionID~'
It should be possible to write a query to join it all together, but I don't have time right now. I will try and update the question later.

Resources