对许多表执行相同的SQL更新语句?

时间:2013-04-09 11:15:05

标签: sql sql-server tsql

嗨我在sql server中有6个不同的表,我想运行以下脚本。是否可以在某种循环中进行?

UPDATE Table
    SET fk =CASE fk
    WHEN 1 THEN 15
    WHEN 2 THEN 16
    WHEN 3 THEN 17
    WHEN 4 THEN 11
    WHEN 5 THEN 12
    WHEN 6 THEN 13
    WHEN 7 THEN 14
    END
    WHERE fk IN (1,2,3,4,5,6,7) 
    UPDATE Table SET fk = fk - 10

2 个答案:

答案 0 :(得分:1)

尝试如下......它会帮助你...

以逗号分隔的方式传递您的表名...

DECLARE @test varchar(max);
Declare @Count int;
DECLARE @intFlag INT
SET @intFlag = 1
set @test = '#temp,#temp1,#temp2,#temp3'; --Table Names Separate by Commas
set @test = Replace(@test, ',', '.')
select @Count = len(@test) - len(replace(@test, '.', ''))
WHILE (@intFlag <= @Count + 1)
BEGIN
Declare @tablename as varchar(100)
Declare @sqlquery as varchar(5000)
Select @tablename = ParseName(@test, @intFlag )
SET @sqlquery = @sqlquery + 'UPDATE ' + @tablename  
SET @sqlquery = @sqlquery + 'SET fk = (CASE fk '    
SET @sqlquery = @sqlquery + 'WHEN 1 THEN 15    '
SET @sqlquery = @sqlquery + 'WHEN 2 THEN 16    '
SET @sqlquery = @sqlquery + 'WHEN 3 THEN 17    '
SET @sqlquery = @sqlquery + 'WHEN 4 THEN 11    '
SET @sqlquery = @sqlquery + 'WHEN 5 THEN 12    '
SET @sqlquery = @sqlquery + 'WHEN 6 THEN 13    '
SET @sqlquery = @sqlquery + 'WHEN 7 THEN 14    '
SET @sqlquery = @sqlquery + 'END)  WHERE fk IN (1,2,3,4,5,6,7)     UPDATE ' + @tablename + ' SET fk = fk - 10'
print @sqlquery
exec(@sqlquery)
SEt @intFlag = @intFlag + 1
END

答案 1 :(得分:0)

除非您编写一个游标,您必须手动获取表名,或者从sys.Tables

中选择系统表中的条件列表名称,否则这是不可能的。

你需要使用动态sql作为NikolaMarkovinović在他的评论中提到的,这样你就可以提供表名作为参数,然后作为表名处理。

像:

CREATE PROCEDURE updTable @Tablename nvarchar(30)
AS
UPDATE @Tablename ... 
Your script here ...
GO

为每个表调用它,如:

EXEC updTable 'yourTableName'

或创建一个光标,为您执行此操作:

DECLARE @TableName VARCHAR(30) 
DECLARE db_cursor CURSOR FOR  
SELECT name 
FROM SYS.Tables 
WHERE name IN ('YourTable_1','YourTable_2' ... , 'YourTable_N')  

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0   
BEGIN   
  updTable @name    
END   

CLOSE db_cursor   
DEALLOCATE db_cursor