此查询用于证明一个概念,我最终将使用该概念定位具有特定值的所有列,然后创建名称/值对以导出到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;
为什么update语句不能识别变量?我错过了什么?
答案 0 :(得分: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)
希望这有帮助