Column-name and/or table-name as parameters

2019-01-09 18:49发布

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

2条回答
forever°为你锁心
2楼-- · 2019-01-09 19:07

This code is a very good sample for dynamic column with cursor, since you can not use '+' in @statement.

ALTER PROCEDURE dbo.spTEST
AS
    SET NOCOUNT ON
    DECLARE @query NVARCHAR(4000) = N''
    DECLARE @inputList NVARCHAR(4000) = ''
    DECLARE @field sysname = 'fn'
    DECLARE @my_cur CURSOR
    EXECUTE SP_EXECUTESQL
        N'SET @my_cur = CURSOR FAST_FORWARD FOR SELECT
            CASE @field
                WHEN ''fn'' then fn
            END
            FROM dbo.vCard WHERE [fn] LIKE ''%''+@query+''%'';OPEN @my_cur;',
        N'@field sysname, @query NVARCHAR(4000), @my_cur CURSOR OUTPUT',
        @field = @field,
        @query = @query,
        @my_cur = @my_cur OUTPUT
    FETCH NEXT FROM @my_cur INTO @inputList
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT @inputList
        FETCH NEXT FROM @my_cur INTO @inputList
    END
    RETURN
查看更多
不美不萌又怎样
3楼-- · 2019-01-09 19:13

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.

查看更多
登录 后发表回答