Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

sql server - Column-name and/or table-name as parameters

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...