Currently I have a working version of a dynamic SQL query without any variables except one (@ColumnHeader
). And am able to get the desired result being a collection of column names in one line separated by comma.
select @ColumnHeader = COALESCE(@ColumnHeader+',','') + '''' + column_name + ''''
from databaseName.Information_Schema.Columns
where table_name = 'Dates'
I am trying to add variables for Database_information_schema
and TableName
.
DECLARE @ColumnHeader varchar(8000)
DECLARE @Database_Information_SchemaColumns varchar(8000) = 'DatabaseName2.Information_Schema.Columns'
DECLARE @TableName varchar(8000) = 'dates'
DECLARE @sqlQuery as nvarchar(max) = 'Select ' + @ColumnHeader + '= COALESCE(' + @ColumnHeader+ +''','','''')+ ''''''''+column_name+'''''''' from ' + @Database_Information_SchemaColumns + 'where table_name = '''+ @TableName + ''''
Print @sqlQuery
EXEC sp_executesql @sqlQuery;
I am getting Null
values and am not sure whats wrong here.
string_agg
to build the comma-delimited list.