1

这个查询是为了证明一个概念,我最终将使用它来定位具有特定值的所有列,然后创建一个名称/值对以导出到 JSON。但我被困住了。

我从 sql 表中查询所有列的列表。然后,我想逐行浏览 Table1 中的列,并使用变量更新值来构造查询。例如,如果 Col4 = "Old text" 读取列表,那么我想设置 Col 4 = "New Text" 的值

DECLARE @c varCHAR(100)
DECLARE ReadData CURSOR
FOR SELECT cname FROM sys.syscolumns WHERE creator = 'dbserver' AND tname = 'Table1' 
    DECLARE @RowCount INT

SET @RowCount = (SELECT COUNT(cname) FROM sys.syscolumns WHERE creator = 'dbserver' AND tname = 'Table1')
OPEN ReadData

DECLARE @I INT // iterator

SET @I = 1 // initialize
WHILE (@I <= @RowCount)
BEGIN
FETCH NEXT ReadData INTO @c

INSERT INTO serverdb.Table2 (cname)VALUES(@c)// this works inserting all 100 columns in the cname column of Table 2

UPDATE serverdb.Table1 SET @c = 'New text' WHERE @c = 'Old text'// this fails with a syntax error. @c is not being interpreted for the query. Note: If I hard code the @c var (for testing)to a known column name, the query works as well

SET @I = @I  + 1
END;

为什么更新语句不能识别变量?我错过了什么?

4

1 回答 1

1

当您使用下面提到的 varibale 时,它​​被视为字符串。

UPDATE serverdb.Table1 SET @c = 'New text' WHERE @c = 'Old text'

您需要创建一个动态查询。使用 execute 方法来执行你的动态查询

declare @sql varchar(999)
SELECT @sql = 'UPDATE serverdb.Table1 SET '+ @c + '= ''New text'' WHERE '+ @c+ ' = ''Old text'' '
execute(@sql)

希望这可以帮助

于 2012-05-24T03:52:55.243 回答