STRING_AGG Issue - sql

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

Related

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 '

when using "SELECT varname = something + something etc. I cannot then do "WHERE varname = ..."

I have:
SELECT KEYWORDS = CAST(USRN AS VARCHAR(15)) + ' ' +
RTRIM(SD) + ' ' + RTRIM(NL.LOCALITY_NAME) + ' ' +
RTRIM(NT.TOWN_NAME) + ' ' + RTRIM(NA.AUTHORITY_NAME)
That gives me what looks like a column, but is not:
I want to have it so my code only selects the rows from KEYWORDS that match whatever the user is typing. Normally, if KEYWORDS was a column, I would write:
SELECT .... WHERE KEYWORDS = '%whateverTheUserIsTyping%'
but I cannot because keywords is not a real column and it is telling me that it does not exist.
How do I get around this? thanks
The column alias KEYWORDS isn't visible to the SQL Engine at the time that the WHERE clause is evaluated. You can just repeat your CAST statment, though.
SELECT
KEYWORDS = CAST(USRN AS VARCHAR(15)) + ' ' +
RTRIM(STREET_DESCRIPTOR) + ' ' + RTRIM(NSG_LOCALITY.LOCALITY_NAME) + ' ' +
RTRIM(NSG_TOWN.TOWN_NAME) + ' ' + RTRIM(NSG_AUTHORITY.AUTHORITY_NAME)
FROM yourTable
WHERE
CAST(USRN AS VARCHAR(15)) + ' ' +
RTRIM(STREET_DESCRIPTOR) + ' ' + RTRIM(NSG_LOCALITY.LOCALITY_NAME) + ' ' +
RTRIM(NSG_TOWN.TOWN_NAME) + ' ' + RTRIM(NSG_AUTHORITY.AUTHORITY_NAME)
LIKE '%whateverTheUserIsTyping%'
You can use derived table with an alias (here Q) and get the result from that by filtering in WHERE clause:
SELECT Q.KEYWORDS FROM (
SELECT KEYWORDS = CAST(USRN AS VARCHAR(15)) + ' ' +
RTRIM(STREET_DESCRIPTOR) + ' ' + RTRIM(NSG_LOCALITY.LOCALITY_NAME) + ' ' +
RTRIM(NSG_TOWN.TOWN_NAME) + ' ' + RTRIM(NSG_AUTHORITY.AUTHORITY_NAME)
) AS Q
WHERE Q.KEYWORDS LIKE '%whateverTheUserIsTyping%'
Because you can't use the column alias in the WHERE clause as you mentioned. Also instead of the KEYWORDS = '%whateverTheUserIsTyping%', you can use LIKE operator.

Incorrect syntax near ']'.?

I have done some debugging on my sql and I cant figure out the maddening error I am getting I have narrowed it down to a couple of lines which I cant see what the problem is, please someone give me some assistance.
I get this error
I am here2
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near
']'.
I am here3
Print 'I am here2'
SET IDENTITY_INSERT c365online_script1.dbo.tCompany ON
declare #cols2 varchar(max)
select #cols2 = (Select Stuff((Select '],[' + C.COLUMN_NAME From INFORMATION_SCHEMA.COLUMNS As C Where C.TABLE_SCHEMA = T.TABLE_SCHEMA And C.TABLE_NAME = T.TABLE_NAME Order By C.ORDINAL_POSITION For Xml Path('')), 1, 2, '') As Columns From INFORMATION_SCHEMA.TABLES As T WHERE T.TABLE_NAME = #tablename)
EXEC('INSERT INTO [' + #Destination_Database_Name + '].[dbo].[' + #tablename + '] (' + #cols2 + ']' + ') SELECT ' + #cols2 + ']' + ' FROM [' + #Source_Database_Name + '].[dbo].[' + #tablename + ']');
Print 'I am here3'
You're missing an opening square bracket here:
... ') SELECT ' + #cols2 + ']' + ' FROM ...
Furthermore I would recommend you switch to using the QuoteName() function instead:
... ') SELECT ' + QuoteName(#cols2) + ' FROM...
You are missing about 3 opening brackets as far as i can tell at
select #cols2 = (Select Stuff((Select '],[
and
(' + #cols2 + ']' // -> either [' + #cols2 + ']' or (' + #cols2 + ')'
and
+ ') SELECT ' + #cols2 + ']' -- -> either ') SELECT [' + #cols2 + ']' or ') SELECT (' + #cols2 + ')'
declare #cols2 nvarchar(max)
select #cols2 = (Select Stuff((Select ',[' + C.COLUMN_NAME + ']'
From INFORMATION_SCHEMA.COLUMNS As C
Where C.TABLE_SCHEMA = T.TABLE_SCHEMA
And C.TABLE_NAME = T.TABLE_NAME
Order By C.ORDINAL_POSITION For Xml Path('')), 1, 1, '') As Columns
From INFORMATION_SCHEMA.TABLES As T
WHERE T.TABLE_NAME = #tablename)
Edit
DECLARE #Destination_Database_Name NVARCHAR(128) = 'Trg_DataBaseName'
DECLARE #tablename NVARCHAR(128) = 'AgressoIFCGLItems'
DECLARE #Source_Database_Name NVARCHAR(128) = 'Configsandpit'
Print 'I am here2'
--SET IDENTITY_INSERT c365online_script1.dbo.tCompany ON
declare #cols2 varchar(max)
select #cols2 = (Select Stuff((Select ',' + QUOTENAME(C.COLUMN_NAME) [text()]
From INFORMATION_SCHEMA.COLUMNS As C
Where C.TABLE_SCHEMA = T.TABLE_SCHEMA
And C.TABLE_NAME = T.TABLE_NAME
Order By C.ORDINAL_POSITION For Xml Path('')), 1, 1, '') As Columns
From INFORMATION_SCHEMA.TABLES As T
WHERE T.TABLE_NAME = #tablename)
DECLARE #sql NVARCHAR(MAX)
SET #sql = 'INSERT INTO ' + QUOTENAME(#Destination_Database_Name) + '.[dbo].' + QUOTENAME(#tablename) + ' (' + #cols2 + ') SELECT ' + #cols2 + ' FROM ' + QUOTENAME(#Source_Database_Name) + '.[dbo].' + QUOTENAME(#tablename) + '';
EXECUTE sp_Executesql #sql
Your need to change you #Sql Statement after you have used QOUTENAME function as it adds the square backets for you, you do not need to concatinate square barckets in your Sql statement.
Result
INSERT INTO [Trg_DataBaseName].[dbo].[TableName] ([Col1],[Col2],[Col3],[Col4],[Col5]) SELECT [Col1],[Col2],[Col3],[Col4],[Col5] FROM [Src_Database].[dbo].[TableName]

Building dynamic self join statements in SQL

Declare #alias as varchar(10)
set #alias = 'fk2'
insert into #Queries(Query, ExecuteOrder)
select top 1 'delete ' + fk1.TableFrom + ' from ' + fk1.TableFrom
+ ' join ' + #alias.TableFrom + ' on ' + fk1.TableFrom+'.'+fk1.FK_Column + ' = ' + fk2.TableFrom + '.ID'
+ ' join ' + fk3.TableFrom + ' on ' + fk2.TableFrom+'.'+fk2.FK_Column + ' = ' + fk3.TableFrom + '.ID'
+ ' join ' + fk4.TableFrom + ' on ' + fk3.TableFrom+'.'+fk3.FK_Column + ' = ' + fk4.TableFrom + '.ID'
+ ' Where ' + fk4.TableFrom + '.' + fk4.FK_Column + ' = ' + #value
,#i
from #FK fk1
join #fk As #alias on #alias.TableFrom = fk1.TableTo
join #fk fk3 on fk3.TableFrom = fk2.TableTo
join #fk fk4 on fk4.TableFrom = fk3.TableTo
I am joining a table to itself to build a resulting query to then be executed from the temp table being inserted into. I am currently specifying the amount of joins but would like to build them dynamically based on another integer value being passed in. The amount of joins will correlate with this integer value. The only problem is I need a unique Alias for each join to then be used above to build the resulting query. Is it possible to use a dynamic Alias as to eliminate the need to hardcode the Alias for each join?

space in a select statement in dynamic query

I have a dynamic query like this :
SET #str_Query = 'SELECT SIM.Item_ID,
SIM.Item_Description,
SU.Short_Description AS Unit,
SIM.Std_Lead_Time,'+
'' ''+' AS Last_Purchase_Rate
FROM FKMS_Item_Master AS SIM
INNER JOIN FKMS_STP_Units SU
ON SIM.Item_Purchase_Unit=SU.Unit_Id' +
' WHERE ' + #str_Condition +
' AND SIM.Location_Id =' + CAST(#aint_Location_Id AS VARCHAR(10)) +
' AND SIM.Item_Deleted =0
AND SIM.Approved_On IS NOT NULL'
+' ORDER BY SIM.Item_Description'
I want to retrieve space as Last_Purchase_Rate
It is showing syntax error in the portion of '' ''+' AS Last_Purchase_Rate
when I execute this query.
If I print this dynamic query, query seems correct. It shows as AS Last_Purchase_Rate with space before AS. Please help.
I would write
...SIM.Std_Lead_Time, '' '' AS Last_Purchase_Rate...
instead of
...SIM.Std_Lead_Time,'+'' ''+' AS Last_Purchase_Rate...
Why not use NULL instead of space and then handle the result in your app?
I.e.,
SET #str_Query = 'SELECT SIM.Item_ID,
SIM.Item_Description,
SU.Short_Description AS Unit,
SIM.Std_Lead_Time,
NULL AS Last_Purchase_Rate, -- and so on.
You could also use CHAR(32):
SET #str_Query = 'SELECT SIM.Item_ID,
SIM.Item_Description,
SU.Short_Description AS Unit,
SIM.Std_Lead_Time,
CHAR(32) AS Last_Purchase_Rate, -- and so on.
You did not escape all quotes.
A working version of your statement would be
SET #str_Query = 'SELECT SIM.Item_ID,
SIM.Item_Description,
SU.Short_Description AS Unit,
SIM.Std_Lead_Time,'
+ ''' '''
+ ' AS Last_Purchase_Rate
FROM FKMS_Item_Master AS SIM
INNER JOIN FKMS_STP_Units SU
ON SIM.Item_Purchase_Unit=SU.Unit_Id' +
' WHERE ' + #str_Condition +
' AND SIM.Location_Id =' + CAST(#aint_Location_Id AS VARCHAR(10)) +
' AND SIM.Item_Deleted =0
AND SIM.Approved_On IS NOT NULL'
+' ORDER BY SIM.Item_Description'
but I find that with a little reformatting, the error is easier to spot
SET #str_Query =
'SELECT SIM.Item_ID '
+ ', SIM.Item_Description '
+ ', SU.Short_Description AS Unit '
+ ', SIM.Std_Lead_Time '
+ ', '' ''' + ' AS Last_Purchase_Rate '
+ 'FROM FKMS_Item_Master AS SIM '
+ ' INNER JOIN FKMS_STP_Units SU '
+ ' ON SIM.Item_Purchase_Unit=SU.Unit_Id '
+ ' WHERE ' + #str_Condition
+ ' AND SIM.Location_Id = ' + CAST(#aint_Location_Id AS VARCHAR(10))
+ ' AND SIM.Item_Deleted =0 '
+ ' AND SIM.Approved_On IS NOT NULL '
+ ' ORDER BY SIM.Item_Description '
Try using tsql function SPACE(1)