更新时间:2023-10-10 20:47:40
在DDL中使用变量,例如@tableName。此外,将名称分成部分并忽略模式只会导致错误。您应该只在SQL批处理参数中使用?替换,并依靠 MSforeachtable
替换:
You cannot use variables, like @tableName, in DDL. Besides, splinting the name into part and ignoring the schema can only result in bugs. You should just use the ''?'' replacement in the SQL batch parameter and rely on the MSforeachtable
replacement:
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';