Reputation: 31
Is it possible to update multiple tables from a query result?
I've tried using a cursor. But it's still not working.
Here's the code :
DECLARE @TableName VARCHAR(MAX)
DECLARE db_cursor CURSOR FOR
SELECT TABLE_NAME
FROM information_schema.columns
WHERE column_name = 'Code1';
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE @TableName
SET Code1 = Code + '_' + Type
FETCH NEXT FROM db_cursor INTO @TableName
END
CLOSE db_cursor
DEALLOCATE db_cursor
Upvotes: 1
Views: 131
Reputation: 3537
I suppose that OP is trying to dynamically build and execute SQL-code for all tables that have column Code1
Solution (one of many) could be:
exec
created expressionsDECLARE @sql_code varchar(max)
DECLARE code_cursor CURSOR FOR
SELECT DISTINCT
'UPDATE '+ TABLE_NAME + ' SET Code1= Code + ''_'' + Type;' AS SQL_CODE
FROM
information_schema.columns -- WHERE column_name = 'Code1';
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @sql_code
WHILE @@FETCH_STATUS = 0
BEGIN
exec(@sql_code)
FETCH NEXT FROM db_cursor INTO @TableName
END
CLOSE db_cursor
DEALLOCATE db_cursor
I did not tested it (of cause - I don't have similar DB) - so be careful.
It's even simpler would be to modify OP code like this:
DECLARE @TableName VARCHAR(MAX)
DECLARE db_cursor CURSOR
FOR SELECT DISTINCT TABLE_NAME -- note DISTINCT here
FROM information_schema.columns WHERE column_name = 'Code1';
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC('UPDATE '+ @TableName + ' SET Code1 = Code + ''_'' + Type') -- note EXEC here
FETCH NEXT FROM db_cursor INTO @TableName
END
CLOSE db_cursor
DEALLOCATE db_cursor
Upvotes: 2