Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Given following snippet (MS SQL):

DECLARE UpdateList CURSOR FOR
SELECT MyColumn FROM MyTable
OPEN UpdateList

Nothing fancy so far. Now I would like to declare two variables where I can write the column's and table's name into. Following, of course, wouldn't work. How can I achieve this?

DECLARE @TableName nchar(20) = 'MyTable'
DECLARE @ColumnName nchar(20) = 'MyColumn'
DECLARE UpdateList CURSOR FOR
SELECT @ColumnName FROM @TableName
OPEN UpdateList

Thx for any tipps sl3dg3

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
201 views
Welcome To Ask or Share your Answers For Others

1 Answer

You'll have to use Dynamic SQL - you can't use parameters as table or column names. So something like:

CREATE TABLE #temp (newcol nvarchar(500)) -- Use the type you're getting out of @TableName
DECLARE @TableName nchar(20) = 'MyTable'
DECLARE @ColumnName nchar(20) = 'MyColumn'

EXEC('INSERT INTO #temp SELECT [' + @ColumnName + '] FROM [' + @TableName + ']')

DECLARE UpdateList CURSOR FOR
SELECT newcol FROM #temp
OPEN UpdateList

Please keep in mind the security and performance issues associated with dynamic SQL - I don't know how you'll be populating the variables, here, and there can be some definite danger in doing this.

EDIT: Added full code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...