Question

I want to get columnnaes of a table in a variable in this form col1,col2,col3

So I used following query

SELECT @cols = COALESCE(@cols + ', ', '') + column_name FROM
INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG='mudb' and TABLE_NAME='mytbl'

I have been successful with above. But when i want to use variable table name. I get problem. I tried

SELECT @cols = COALESCE(@cols + ', ', '') + column_name FROM
INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG='mudb' and TABLE_NAME=@tbl

But it gives null result. Then I teid to use EXECUTE 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

Then it gives me error Must declare the scalar variable "@cols" but @cols is declared

Was it helpful?

Solution

@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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top