在SQL Server(Transact)中从外部游标访问变量时遇到困难

时间:2017-10-30 14:22:36

标签: sql sql-server tsql cursor

下面是我的代码,目前它并没有做太多事情,但我的最终目标是查看数据库中的每个类似文本的字段,检查它是否存在特定条件并在必要时进行修改。

我一直在朝这个方向努力,一切都顺利,直到我真的试图检索列中的值。

当我尝试set @CurrentValue时会出现问题。 top 1代码只是暂时的,直到我稍后扩展代码,但这不是问题。在测试中,我发现在尝试使用内部@TableName循环中的while时出错。

Must declare the table variable "@TableName".

我不是程序化Transact SQL的专家。有没有办法从这个位置访问这个变量?

--Edit following config lines as necessary
USE mytable
DECLARE @SchemaName SYSNAME = 'dbo'
DECLARE @TableName SYSNAME

DECLARE TableCursor CURSOR FOR
SELECT t.name 
  FROM sys.tables AS t
  INNER JOIN sys.schemas AS s
  ON t.[schema_id] = s.[schema_id]
  WHERE s.name = @SchemaName
  and lower(t.name) like 'online%';

OPEN TableCursor

FETCH NEXT FROM TableCursor
INTO @TableName

    WHILE @@FETCH_STATUS = 0
    BEGIN

        PRINT '-----'
        PRINT @TableName
        PRINT '-----'

        DECLARE MatchingColumns CURSOR LOCAL FOR
        SELECT COLUMN_NAME
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE 
        TABLE_NAME = @TableName
        AND
        DATA_TYPE in ('nvarchar', 'varchar', 'ntext', 'text', 'nchar', 'char');

        DECLARE @ColumnName NVARCHAR(MAX)

        OPEN MatchingColumns

        FETCH NEXT FROM MatchingColumns
        INTO @ColumnName

        WHILE @@FETCH_STATUS = 0
        BEGIN

            DECLARE @CurrentValue NVARCHAR(MAX)

            set @CurrentValue = (
                select top 1 @ColumnName
                from @TableName
            )


            PRINT @ColumnName

            FETCH NEXT FROM MatchingColumns
            INTO @ColumnName

        END

        CLOSE MatchingColumns
        DEALLOCATE MatchingColumns

        FETCH NEXT FROM TableCursor
        INTO @TableName


    END

CLOSE TableCursor
DEALLOCATE TableCursor

1 个答案:

答案 0 :(得分:0)

替换

set @CurrentValue = (
                select top 1 @ColumnName
                from @TableName
            )

declare @cmd nvarchar(200)
set @cmd  = N'SELECT TOP 1  @CurrentValue=' +  @ColumnName + ' from ' + @TableName
EXECUTE @CurrentValue = sp_executesql @cmd, N'@CurrentValue VARCHAR(MAX)',  @CurrentValue OUT