2012-07-06 56 views
2

我尝试添加一个新列列2到test_tbl并设置默认值的列“N/A”非空。该声明如下:如果存在alter table语句有没有空或默认值不起作用

if not exists (select 1 from syscolumns where object_name(id) = 'test_tbl' and name = 'column2') 
begin 
    alter table test_tbl add column2 varchar(20) default 'N/A' not null 
end 

的错误是

Could not execute statement. 
Column names in each table must be unique. Column name 'column2' in table 'test_tbl' is specified more than once. 
Sybase error code=2705 
Severity Level=16, State=3, Transaction State=1 
Line 4 

但是,如果我添加一列是可空

if not exists (select 1 from syscolumns where object_name(id) = 'test_tbl' and name = 'column2') 
begin 
    alter table test_tbl add column2 varchar(20) null 
end 

它可以工作。我对这些很满意。 我搜索了一些标签,并知道动态SQL可以工作。

误差归一化过程中被升高(如分析树是 被转换成归一化的查询树),而不是在执行 。动态sql的内容只有在实际调用 之后才会被处理,从而避免了错误。

在Sybase DOC大约如果...否则

当ALTER TABLE,创建表,或创建视图命令发生if ... else块内 ,Adaptive Server创建作为模式 表或视图在确定条件是否为真之前。如果表或视图已存在,则此 可能会导致错误。

我想知道为什么可以运行nullable column语句而没有错误!

回答

4

我看到的Sybase ASE相同的行为15

我不能为您提供超乎你已经从Sybase载文引述的解释,但是你可以通过脚本包调用一致的行为改变表中一个execute()语句如下

if not exists (select 1 from syscolumns where object_name(id) = 'tbl_test' and name = 'column2') 
begin  
    execute(" 
     alter table tbl_test add column2 varchar(20) default 'N/A' not null 
    ") 
end 

我的猜测是,服务器能够执行ALTER语句之前评估在这种情况下,if...else声明。

0

你应该写go..

请检查下面的代码它的工作对我罚款

IF EXISTS (SELECT 1 FROM sysobjects WHERE name = 'a_table' AND type = 'U') 
drop table a_table 
go 
CREATE TABLE a_table (col1 int not null,col2 int null) 
go