如何使用作为列数据生成的更新语句更新表?

时间:2014-04-08 19:44:38

标签: sql-server-2008 sql-update

我有以下代码:

SELECT 'UPDATE table3 ENTRYNAME = '''+CONVERT(VARCHAR(5000),
 riv.description)+''''+' WHERE id = '+CONVERT(VARCHAR(50), e.ID)+';'  AS 
 Update_Statement
FROM table1 AS riv 
JOIN table2 AS e
ON riv.Code = e.Code
AND  riv.definitioncode  = 'RIV'
AND riv.Description <> e.Description
AND riv.categoryID <> 0
;

这会生成如下所示的列值:

UPDATE table3 SET ENTRYNAME = 'new column data here' WHERE id = 50005;

我希望能够在生成后运行列数据。

我将如何做到这一点?

它看起来像这样:

DECLARE @update_Statement --update statement

DECLARE db_cursor CURSOR FOR
SELECT 'UPDATE table3 ENTRYNAME = '''+CONVERT(VARCHAR(5000),
riv.description)+''''+' WHERE id = '+CONVERT(VARCHAR(50), e.ID)+';'  AS 
Update_Statement
FROM table1 AS riv 
JOIN table2 AS e
ON riv.Code = e.Code
AND  riv.definitioncode  = 'RIV'
AND riv.Description <> e.Description
AND riv.categoryID <> 0

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @update_statement

WHILE @@FETCH_STATUS = 0 
BEGIN 
EXECUTE @update_statement
END
CLOSE db_cursor
DEALLOCATE db_cursor

0 个答案:

没有答案