@cols
may be declared in the scope of the script you are running. It is not declared in the scope of the dynamic SQL. Variables are not inherited from one level to another.
So, you want to pass it into the execution environment, which you can do with sp_executesql
:
set @FullStatement='SELECT @cols = COALESCE(@cols + '', '', '''') +
column_name FROM INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG=''mudb''
and TABLE_NAME=@tbl'
PRINT @FullStatement
EXECUTE sp_executesql @FullStatement, N'@Cols varchar(8000) output, @Tbl varchar(8000)',
@cols = @cols, @tbl = 'MyTable';
That is how you get the execute statement to work. However, that method of concatenating column will not work in dynamic SQL.