Add a column if it doesn't exist to all tables?
我正在使用SQL Server 2005/2008。如果列还不存在,我需要向表中添加一列。这将应用于给定数据库中的所有表。我希望我能接近,但我对这个解决方案有异议。
怎么能做到?
以下是我的资料:
1 2 3 4 5 6 7 8 9 10 | EXEC sp_MSforeachtable ' declare @tblname varchar(255); SET @tblname = PARSENAME("?",1); if not exists (select column_name from INFORMATION_SCHEMA.columns where table_name = @tblname and column_name = ''CreatedOn'') begin ALTER TABLE @tblname ADD CreatedOn datetime NOT NULL DEFAULT getdate(); end ' |
但我有错误:
Error 102: Incorrect syntax near '@tblname'.
Incorrect syntax near 'CreatedOn'.
Incorrect syntax near '@tblname'.
Incorrect syntax near 'CreatedOn'.
... and so on, for each table.
号
不能在DDL中使用变量,如@tablename。此外,将名称拆分成部分并忽略模式只能导致错误。你应该只使用""?""在sql batch参数中进行替换,并依靠
1 2 3 4 5 6 7 | EXEC sp_MSforeachtable ' if not exists (select * from sys.columns where object_id = object_id(''?'') and name = ''CreatedOn'') begin ALTER TABLE ? ADD CreatedOn datetime NOT NULL DEFAULT getdate(); end'; |
。
您需要混合一些动态SQL。这应该有效:
1 2 3 4 5 6 7 8 9 10 11 12 | EXEC sp_MSforeachtable ' declare @tblname varchar(255); SET @tblname = PARSENAME("?",1); declare @sql nvarchar(1000); if not exists (select column_name from INFORMATION_SCHEMA.columns where table_name = @tblname and column_name = ''CreatedOn'') begin set @sql = N''ALTER TABLE '' + @tblname + N'' ADD CreatedOn datetime NOT NULL DEFAULT getdate();'' exec sp_executesql @sql end ' |
可能是这样:
1 2 3 4 5 6 7 8 9 10 | EXEC sp_MSforeachtable ' declare @tblname varchar(255); SET @tblname = PARSENAME("?",1); if not exists (select column_name from INFORMATION_SCHEMA.columns where table_name = @tblname and column_name = ''CreatedOn'') begin ALTER TABLE [?] ADD CreatedOn datetime NOT NULL DEFAULT getdate(); end ' |
号
?
或者像这样:
1 2 3 4 5 6 7 | EXEC sp_MSforeachtable ' if not exists (select column_name from INFORMATION_SCHEMA.columns where table_name = ''?'' and column_name = ''CreatedOn'') begin ALTER TABLE [?] ADD CreatedOn datetime NOT NULL DEFAULT getdate(); end ' |