2

嗨,我在 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
4

2 回答 2

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
于 2013-04-09T11:53:47.843 回答
0

不,这是不可能的,除非您编写一个游标,在该游标中您必须手动获取表名,或者通过从系统表中选择表名直到条件sys.Tables


您将需要使用 Nikola Markovinović 在他的评论中提到的动态 sql,以便您可以将表名作为参数提供,然后将其作为表名处理。

像:

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
于 2013-04-09T11:16:35.273 回答