如果所有表都不存在,添加列吗? [英] Add a column if it doesn't exist to all tables?

查看:77
本文介绍了如果所有表都不存在,添加列吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SQL Server 2005/2008。我需要向表中添加一列(如果尚不存在)。这将应用于给定数据库中的所有表。我希望我能近在咫尺,但是我对这个解决方案有疑问。

I'm using SQL Server 2005/2008. I need to add a column to a table if it does not yet exist. This will apply to all tables in a given database. I hoped I was close, but I'm having issues with this solution.

这怎么办?

这就是我所拥有的:

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
'

但是我得到了错误:


错误102:'@tblname'附近的语法不正确。
CreatedOn附近的语法不正确。
@tblname附近的语法不正确。
CreatedOn附近的语法不正确。
...依此类推,对于每个表。

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批处理参数中使用?替换,并依靠 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';

这篇关于如果所有表都不存在,添加列吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆