Adding order by for XML throws error - sql

Here is my actual query
SELECT
aces.ProductID,'<p>' +
Replace(STUFF((SELECT DISTINCT ', ' + CAST(A.year AS VARCHAR(4)) + ' ' + A.make + ' ' + A.model + ' ' + A.enginebase_new
FROM ACES_Data A
WHERE A.ProductID = aces.ProductID
FOR XML PATH('')), 1, 1, ''), ',', '<br>')
+ '</p><p>' + i.[Subline Code] + '<br>' + i.[Subline Name] + '</p>' AS FullDescription
FROM
ACES_Data aces
LEFT OUTER JOIN
InventoryPricing i ON aces.part_number = i.PART
WHERE
aces.ProductID IS NOT NULL
AND aces.MakeModelMappingID IS NOT NULL
GROUP BY
aces.ProductID, i.[Part Description], i.[Subline Code], i.[Subline Name]
Now adding order by before XML throws an error.
Please look below updated query
SELECT
aces.ProductID,'<p>' +
Replace(
STUFF
(
(
SELECT
distinct ', ' + Cast(A.year as varchar(4)) + ' ' + A.make +' ' + A.model + ' ' + A.enginebase_new
FROM
ACES_Data A
Where
A.ProductID=aces.ProductID
order by A.make,A.year asc
FOR XML PATH('')
),1,1,'')
,',',
'<br>'
)
+ '</p><p>' + i.[Subline Code] + '<br>'+ i.[Subline Name] + '</p>' As FullDescription
from ACES_Data aces
Left outer join InventoryPricing i
on aces.part_number = i.PART
where aces.ProductID is not null
and aces.MakeModelMappingID is not null
Group By aces.ProductID,i.[Part Description],i.[Subline Code],i.[Subline Name]
on inserting
Where A.ProductID=aces.ProductID **order by A.make,A.year asc** FOR XML PATH('')
it gives me error as
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

Since enginebase_new & model is not part of Order by you cannot use DISTINCT in Select.
Use Group by instead of DISTINCT to remove duplicates
SELECT ', ' + Cast(A.year AS VARCHAR(4)) + ' ' + A.make
+ ' ' + A.model + ' ' + A.enginebase_new
FROM ACES_Data A
WHERE A.ProductID = aces.ProductID
GROUP BY A.year,
A.make,
A.model,
A.enginebase_new
ORDER BY A.make,
A.year ASC
FOR XML PATH('')

Related

When make concatenation sql string query , error has occurred because single quote

SET #InventoryQuery = N'SELECT * FROM
(
SELECT Inven.Inventory_ID As ID,Inven.Inventory_ID As Number, Inventory_Date As ActionDate, ''Inventory'' AS [ActionType], IsNull(Sum(Product_Qty),0) Product_Qty, P.Product_Desc_ENG + '' ('' + P.Product_Weight + '')'' Product_Desc_ENG
FROM CRM.Product P
INNER JOIN [crm].[InventoryDetail] InvenDet ON P.Product_ID = InvenDet.Product_ID
INNER JOIN [crm].[Inventory] Inven ON Inven.Inventory_ID = InvenDet.Inventory_ID
WHERE Inven.Customer_Id = ' + CAST(#CustomerID AS VARCHAR(10)) +
' AND ( Inven.Inventory_Date BETWEEN ' + CONVERT(VARCHAR(20), #StartDate, 121) + '
AND ' + CONVERT(VARCHAR(20), #EndDate, 121) + ' ) GROUP BY Inven.Inventory_ID, Inventory_Date,P.Product_Desc_ENG,P.Product_Weight
) y
pivot
(
sum(Product_Qty)
for Product_Desc_ENG in (' + #cols + N')
) p2 '

problem in executing dynamic query using pivot with syntax error Incorrect syntax near ' + '

I want to Create a query with dynamic query and in this query i use concat some cells , when use concat like 'N'subject:' + ' ' + ContentProductionTitle' i get syntax error
error : Incorrect syntax near ' + '.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.KeyWordTitle)
FROM TBL_CU_ContentProduction_KeyWord c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT ' + #cols + ' from
(
select
isnull((select N'subject:' + ' ' + ContentProductionTitle
from Tbl_Cu_ContentProductionCalendar
where ContentProductionCalendarID = a.ActionSubjectId ),'')
+' ' +
isnull((select top 1 N'author:'+ p.FullName + ' ' from users.TblProfiles as p
where p.UserId= a.ActionUserID ),'') +' ' +
isnull((select top 1 N'edit bye:' + ' ' + p.FullName from users.TblProfiles as p
where p.UserId= a.CheckAgain ) ,'') as title
, a.ActionDateTo
, k.KeyWordTitle
from TBL_CU_ContentProduction_KeyWord as k
inner join Tbl_CU_ContentProduction as cp
on k.ContentGUID = cp.ContentGUID
inner join Tbl_Cu_ActionContentProduction as a
on a.ContentGUID = cp.ContentGUID
) x
pivot
(
max(ActionDateTo)
for KeyWordTitle in (' + #cols + ')
) p '
execute(#query)
you need to escape single quote inside your query string with '':
set #query = 'SELECT ' + #cols + ' from
(
select
isnull((select N''subject:'' + '' '' + ContentProductionTitle
from Tbl_Cu_ContentProductionCalendar
where ContentProductionCalendarID = a.ActionSubjectId ),'''')
+'' '' +
isnull((select top 1 N''author:''+ p.FullName + '' '' from users.TblProfiles as p
where p.UserId= a.ActionUserID ),'''') +'' '' +
isnull((select top 1 N''edit bye:'' + '' '' + p.FullName from users.TblProfiles as p
where p.UserId= a.CheckAgain ) ,'''') as title
, a.ActionDateTo
, k.KeyWordTitle
from TBL_CU_ContentProduction_KeyWord as k
inner join Tbl_CU_ContentProduction as cp
on k.ContentGUID = cp.ContentGUID
inner join Tbl_Cu_ActionContentProduction as a
on a.ContentGUID = cp.ContentGUID
) x
pivot
(
max(ActionDateTo)
for KeyWordTitle in (' + #cols + ')
) p '

STRING_AGG Issue

I was working with SQL Server 2017 and I used the following query,
select
'select s.' + string_agg (c.source_column + ', t.' + c.target_column, ', ') +
' from ' + t.source_table + ' s' +
' join ' + t.target_table + ' t' +
' on ' + string_agg('t.' + c.target_column + ' = s.' + c.source_column, ' and ') +
';' as query
from configuration_tables t
join configuration_columns c on c.id_configuration_tables = t.id_configuration_tables
group by t.source_table, t.target_table
order by t.source_table, t.target_table;
The query is used to get the list of columns in a string for each table name.
I have to move to 2016 due to some issues, I modified the query as below,
select
distinct 'select ' + STUFF((select ',' + 's.[' + c1.source_column + '],t.[' + c1.target_column + ']'
from recon_configuration_columns c1 where c1.id_recon_configuration_table = c.id_recon_configuration_table FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,1,'')
+ ' from ' + t.source_table + ' s' +
' join ' + t.target_table + ' t' +
' on ' + STUFF((select ' and ' + 's.[' + c1.source_column + '] = t.[' + c1.target_column + '] ' from recon_configuration_columns c1
where c1.id_recon_configuration_table = c.id_recon_configuration_table FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,5,'')
from
recon_configuration_tables t
join recon_configuration_columns c on c.id_recon_configuration_table = t.id_recon_configuration_table
I would like to know whether the query I changed is a standard one, also it wont create any problems in long run and always both queries should return the same results.
Thanks for your support

Get specific columns from xml path

I have this query here:
SELECT
T.AKSIONERET,
sd.Identification_No, sd.Date_Of_Incorp,
sd.Ownership_Desc, sd.Ownership_Code,
sd.Subject_Name_Code, sd.Subject_Name,
sd.Subject_Type_Code,
LEFT(sd.Object_Desc, 3999) AS Object_Desc,
sd.Subject_Status_Name, sd.Subject_Name,
nr2.NACE_Code, nr2.NACE_PARENT, nr2.Description,
sd.Subject_Type_Name, sd.Subject_Status_Name,
sd.Subject_Type_Name, f.Place_Of_Registration, sd.Object_Desc
FROM
NRC_Subject_DEF AS sd
LEFT JOIN
NRC_Nace_REV2 AS nr2 ON nr2.Subject_DEF_Code = sd.Subject_DEF_Code
LEFT JOIN
NRC_ForeignCompany AS f ON sd.ForeignCompany_Code = f.ForeignCompany_Code
LEFT JOIN
(SELECT
SDP.Subject_DEF_Code,
(SELECT
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc AS FullAksionerCitizenship
FROM
NRC_PeopleAddress P
INNER JOIN
NRC_SubjectDefPeople SDP1 ON SDP1.People_Code = P.People_Code
WHERE
SDP1.Subject_DEF_Code = SDP.Subject_DEF_Code
GROUP BY
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc
FOR XML PATH('')) AS AKSIONERET
FROM
NRC_SubjectDefPeople SDP
WHERE
SDP.Groyp_Type IN (1,2)
GROUP BY
SDP.Subject_DEF_Code) AS T ON T.Subject_DEF_Code = SD.SUBJECT_DEF_CODE
I need to retrieve, instead of T.AKSIONERET the FullAksionerCitizenship which I get from the for xml path.
I know I have to do some other SELECT but I kept getting errors, syntax errors.
Could someone help?
Thanks in advance
I'm quite sure, that there could be a better design and I'm not able to run this against test data off course, but this could work:
SELECT
T.AKSIONERET,
T2.FullAksionerCitizenship,
sd.Identification_No, sd.Date_Of_Incorp,
sd.Ownership_Desc, sd.Ownership_Code,
sd.Subject_Name_Code, sd.Subject_Name,
sd.Subject_Type_Code,
LEFT(sd.Object_Desc, 3999) AS Object_Desc,
sd.Subject_Status_Name, sd.Subject_Name,
nr2.NACE_Code, nr2.NACE_PARENT, nr2.Description,
sd.Subject_Type_Name, sd.Subject_Status_Name,
sd.Subject_Type_Name, f.Place_Of_Registration, sd.Object_Desc
FROM
NRC_Subject_DEF AS sd
LEFT JOIN
NRC_Nace_REV2 AS nr2 ON nr2.Subject_DEF_Code = sd.Subject_DEF_Code
LEFT JOIN
NRC_ForeignCompany AS f ON sd.ForeignCompany_Code = f.ForeignCompany_Code
LEFT JOIN
(SELECT
SDP.Subject_DEF_Code,
(SELECT
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc AS FullAksionerCitizenship
FROM
NRC_PeopleAddress P
INNER JOIN
NRC_SubjectDefPeople SDP1 ON SDP1.People_Code = P.People_Code
WHERE
SDP1.Subject_DEF_Code = SDP.Subject_DEF_Code
GROUP BY
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc
FOR XML PATH('')) AS AKSIONERET
FROM
NRC_SubjectDefPeople SDP
WHERE
SDP.Groyp_Type IN (1,2)
GROUP BY
SDP.Subject_DEF_Code) AS T ON T.Subject_DEF_Code = SD.SUBJECT_DEF_CODE
--here starts the new block (difficult for me without knowing your db...)
LEFT JOIN
(SELECT
(SELECT
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc AS FullAksionerCitizenship
FROM
NRC_PeopleAddress P
INNER JOIN
NRC_SubjectDefPeople SDP1 ON SDP1.People_Code = P.People_Code
WHERE
SDP1.Subject_DEF_Code = SDP.Subject_DEF_Code
GROUP BY
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc
) AS FullAksionerCitizenship
FROM
NRC_SubjectDefPeople SDP
WHERE
SDP.Groyp_Type IN (1,2)
GROUP BY
SDP.Subject_DEF_Code) AS T2 ON T2.Subject_DEF_Code = SD.SUBJECT_DEF_CODE

dynamic sql query with FOR XML Path

I have following sql and when i run this its throw error
Incorrect syntax near '1'.
declare #sql nvarchar(max)
set #sql =N'SELECT PT.P_Name as Prisoner_Type,
PE.PID_No,PE.Jail_Code,PE.Entry_Year,Convert(varchar(10),PE.Admission_Date,103) Admission_Date,PE.JID_No,Convert(varchar(10),PE.Release_Date,103) Release_Date ,
PM.Prisoner_Name, SUBSTRING(PM.Father_Name, 0, 17)as Father_Name, PM.Mother_Name,PM.Spouse_Name,PM.Caste_Code,
PM.Religion_Code,PM.Occupation_Code,PM.Qualification,PM.Tendency_Type,PM.Risk_Type,PM.Annual_Income_Code,PM.Marital_Status_Code,PM.Id_Mark,
PM.Sex_Code,PM.Nationality_Code,PM.Off_Code,PM.Present_Add, Age as age ,PM.Permt_Add, LS.Location AS Location
,NT.Nation_Name , JT.Jail_Address
,OT.Offence_Name,QT.Qualification as quali ,IT.Annual_Income_Range,CT.Caste_Name
,RT.Religion_Name,MT.Marital_Status_Name,OFT.Occ_Name AS Occupation
, STUFF(( SELECT '', '' + cc.Act_Sec AS [text()]
FROM CourtCases cc
WHERE
cc.PID_NO = PE.PID_NO and ('','' + Replace(pe.Case_No,''$'','','') +'','' LIKE ''%,'' + CONVERT(VARCHAR, cc.Case_No) + '',%'') group by cc.Act_Sec
FOR XML PATH('''') ),'+ cast(1 as nvarchar(10))+', '+cast(1 as nvarchar(10))+', '''' )
AS [Act_Sec]
, STUFF(( SELECT '', '' + Convert(varchar(10),CC.Fir_Date,103) AS [text()]
FROM CourtCases cc
WHERE
cc.PID_NO = PE.PID_NO and ('','' + Replace(pe.Case_No,''$'','','') +'','' LIKE ''%,'' + CONVERT(VARCHAR, cc.Case_No) + '',%'') group by Convert(varchar(10),CC.Fir_Date,103)
FOR XML PATH('''') ),'+ cast(1 as nvarchar(10))+', '+cast(1 as nvarchar(10))+', '''' )
AS [Fir_Date]
,STUFF(( SELECT '', '' + FIR_No AS [text()]
FROM CourtCases cc
WHERE
cc.PID_NO = PE.PID_NO and ('','' + Replace(pe.Case_No,''$'','','') +'','' LIKE ''%,'' + CONVERT(VARCHAR, cc.Case_No) + '',%'') group by FIR_No
FOR XML PATH('''') ),'+ cast(1 as nvarchar(10))+', '+cast(1 as nvarchar(10))+', '''' )
AS [FIR_No]
, STUFF(( SELECT '', '' + ct.Court_Name AS [text()]
FROM CourtCases cc inner join Court_Tab as ct
ON cc.Court_Code=convert(nvarchar(50),ct.Court_Code)
WHERE
cc.PID_NO = PE.PID_NO and ('','' + Replace(pe.Case_No,''$'','','') +'','' LIKE ''%,'' + CONVERT(VARCHAR, cc.Case_No) + '',%'') group by ct.Court_Name
FOR XML PATH('''') ),'+ cast(1 as nvarchar(10))+', '+cast(1 as nvarchar(10))+', '''' )
AS [Court_Name]
, STUFF(( SELECT '', '' + pt.PS_Name AS [text()]
FROM CourtCases cc inner join PS_Tab as pt
ON convert(nvarchar(50),cc.PS_Code)=convert(nvarchar(50),pt.PS_Code)
WHERE
cc.PID_NO = PE.PID_NO and ('','' + Replace(pe.Case_No,''$'','','') +'','' LIKE ''%,'' + CONVERT(VARCHAR, cc.Case_No) + '',%'') group by pt.PS_Name
FOR XML PATH('''') ),'+ cast(1 as nvarchar(10))+', '+cast(1 as nvarchar(10))+', '''' )
AS [PS_Name]
FROM PrisonMaster AS PM
INNER JOIN PrisonerEntry AS PE ON PE.PID_No = PM.PID_No AND PE.Jail_Code='+cast(#JailCode as nvarchar) +
'INNER JOIN Nation_Tab AS NT ON PM.Nationality_Code = NT.Nation_Code
INNER JOIN Sex_Tab AS S ON PM.Sex_Code = S.Sex_Code
INNER JOIN Jail_Tab AS JT ON PE.Jail_Code = JT.Jail_Code
INNER JOIN Prisoner_Tab AS PT ON PE.Prisoner_Type=PT.P_Type
INNER JOIN Loc_Status AS LS ON PE.Location=LS.Loc_Status
left JOIN Offence_Tab AS OT ON OT.Offence_Code=PM.Occupation_Code
left JOIN Qualification_Tab AS QT ON QT.Q_Code=PM.Qualification
left JOIN Income_Tab AS IT ON IT.Annual_Income_Code=PM.Annual_Income_Code
left JOIN Caste_Tab AS CT ON CT.Caste_Code=PM.Caste_Code
LEFT JOIN Religion_Tab AS RT ON RT.Religion_Code=PM.Religion_Code
LEFT JOIN Marital_Tab AS MT ON MT.Marital_Status_Code=PM.Marital_Status_Code
LEFT JOIN Occupation_Tab AS OFT ON OFT.Occ_Code=PM.Occupation_Code
WHERE
PE.Admission_Date BETWEEN '+cast(#DATE1 as nvarchar(50))+' and '+ cast(#DATE2 as nvarchar(50))
exec (#sql)
What the ... is this + cast(1 as nvarchar(10))+ ?
Just do + '1' + or even better just add the 1 into your string.