1

I got this dynamic code:

declare @TableName varchar(100)='Customer'
declare @DestinationcolumnList  NVARCHAR(MAX)
DECLARE @ServerName NVARCHAR(100) = '----'
DECLARE @SourceDatabase NVARCHAR(100) = 'Staging'
DECLARE @DestinationDatabase NVARCHAR(100) = 'History'
declare @SQL NVARCHAR(MAX)
set @SQL='
select  
        '+@DestinationcolumnList+' = coalesce('+@DestinationcolumnList+', '''') +'',''+ char(13) + char(10) + quotename(cast(d.COLUMN_NAME as varchar(128)))
from ['+@ServerName+'].['+@DestinationDatabase+'].INFORMATION_SCHEMA.COLUMNS d
inner join ['+@ServerName+'].['+@SourceDatabase+'].INFORMATION_SCHEMA.COLUMNS s 
        on d.TABLE_NAME = s.TABLE_NAME  
        and s.COLUMN_NAME = d.COLUMN_NAME
where   d.TABLE_NAME = '''+@TableName+'''
order by d.ORDINAL_POSITION
'
exec sp_executesql @SQL
select @DestinationcolumnList

its giving NULL value. when I execute same code without dynamic SQL its working fine. How scope of the variable works in dynamic SQL.

Thanks in advance.

2
  • @DestinationcolumnList what value passing this variable Jul 6, 2015 at 13:45
  • Thanks for the reply, @DestinationcolumnList containts column names from INFORMATION_SCHEMA.COLUMNS where ='Customer' Jul 6, 2015 at 13:49

1 Answer 1

3

In Dynamic SQL, variables declared outside the dynamic string are used to build a string, they are not used as a part of the string, so they cannot be used the way you are trying to do it: doing the undocumented trick of concatenating a variable with itself to produce a single string in a SELECT statement.

If you made the variable declaration part of the string, it should work:

set @SQL='
declare @DestinationcolumnList  NVARCHAR(MAX);

select  
        @DestinationcolumnList = coalesce(@DestinationcolumnList, '''') +'',''+ char(13) + char(10) + quotename(cast(d.COLUMN_NAME as varchar(128)))
from ['+@ServerName+'].['+@DestinationDatabase+'].INFORMATION_SCHEMA.COLUMNS d
inner join ['+@ServerName+'].['+@SourceDatabase+'].INFORMATION_SCHEMA.COLUMNS s 
        on d.TABLE_NAME = s.TABLE_NAME  
        and s.COLUMN_NAME = d.COLUMN_NAME
where   d.TABLE_NAME = '''+@TableName+'''
order by d.ORDINAL_POSITION;

select @DestinationcolumnList;
'

exec sp_executesql @SQL
1
  • Thanks for the reply. Now I am able to get DestinationcolumnList values. can you please explain bit more about difference between declaring variable outside dynamic sql and inside dynamic sql. I am new to dynamic sql. Thanks. Jul 6, 2015 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.