我在更新表中的某些列值时遇到问题。在我的数据库中有许多表,我必须更新那些具有名称为“Col1”的列的表。
如果我这样做
exec sp_msforeachtable 'UPDATE ? SET Col1=
case when Col1 = "ppp" then "qqq"
when Col1 = "aaa" then "xxx"
end
'
它会将错误消息报告为
消息207,级别16,状态1,行1 列名称“col1”无效。
怎么办?
答案 0 :(得分:2)
如果必须使用sp_msforeachtable,则可以根据列的存在情况有条件地运行代码。
即。
exec sp_msforeachtable '
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMS WHERE COLUMN_NAME =''Col1'' AND TABLE_NAME = ''?'')
BEGIN
UPDATE ? SET Col1=
case when Col1 = "ppp" then "qqq"
when Col1 = "aaa" then "xxx"
end
END
'
或者,更好的是:
DECLARE @myScripts TABLE(
id INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
sql VARCHAR(max)
)
DECLARE @max INT,
@i INT,
@SQL VARCHAR(MAX)
INSERT INTO @myscripts(sql)
SELECT 'UPDATE [' + tablename + '] SET Col1=
case when Col1 = "ppp" then "qqq"
when Col1 = "aaa" then "xxx"
end'
FROM [INFORMATION_SCHEMA].TABLES WHERE TABLE_NAME IN ('table1','table2','table3','table4')
SELECT @max = @@ROWCOUNT, @i = 1
WHILE @i <= @max
BEGIN
SELECT @SQL = Script
FROM @myScripts
WHERE ID = @i
EXEC sp_executesql @statement = @SQL
SET @i = @i + 1
END
答案 1 :(得分:1)
exec sp_msforeachtable
@command1=
'
BEGIN
UPDATE ? SET Col1=
case when Col1 = "ppp" then "qqq"
when Col1 = "aaa" then "xxx"
END
END
'
@whereand='AND o.id in (select object_id from sys.columns c where c.name=''Col1'')'
whereand将过滤发送给命令的内容,因此您可以自由执行命令,因为只知道将引用具有Col1的表。