0

My problem might be a little strange.

I have a variable column name (can have different but same position)

Later I want to use this column to take the information.

So I put in a variable the column name

Set @name = (Select COLUMN_NAME From INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Test' AND ORDINAL_POSITION = 1)

Then I want to get the information from this column:

EXEC('SELECT ' + @name + ' FROM Test Where id = 1')

This works but i need to put the result in another variable to be able to use it. Or I can't find the way to do it.

I don't want to create a table to put the result, I want to find another way.

How can I set the exec in a variable?

Thanks

4

1 回答 1

0

您可以为此使用全局临时表

DECLARE @name SYSNAME

SELECT @name = COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Test' AND ORDINAL_POSITION = 1

EXEC('SELECT ' + @name + ' INTO ##tmp FROM sys.objects')

SELECT * FROM ##tmp
于 2013-10-29T09:23:55.557 回答