首页 文章

如果存在,alter table语句不为null或默认值不起作用

提问于
浏览
3

我尝试将一个新列 column2 添加到 test_tbl 中,并使用默认值 'N/A'not null 设置该列 . 声明如下:

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

但是如果我添加一列 nullable .

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中关于if ... else

在if ... else块中发生alter table,create table或create view命令时,Adaptive Server会在确定条件是否为true之前为表或视图创建架构 . 如果表或视图已存在,这可能会导致错误 .

我想知道为什么可以为空的列语句可以无错误地执行!

2 回答

  • 4

    我在Sybase ASE 15上看到了相同的行为

    除了您从Sybase Documentaiton引用的内容之外,我无法向您提供解释,但是您可以通过在execute()语句中包含对alter table的调用来编写一致行为,如下所示

    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
    

相关问题