好的,所以Sybase(12.5.4)将允许我执行以下操作以删除已存在的表:

IF EXISTS (
    SELECT 1
    FROM sysobjects
    WHERE name = 'a_table'
    AND type = 'U'
)
DROP TABLE a_table
GO

但是,如果我尝试对表创建执行相同操作,我总是会收到警告,表已经存在,因为它继续并尝试创建我的表并忽略条件语句。试试两次运行以下语句,你会明白我的意思:

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

运行上述操作会产生以下错误:

  

SQL Server错误(localhost)   错误:2714在线:7消息:有   已经是一个名为'a_table'的对象   数据库。

与此有什么关系?!

有帮助吗?

解决方案

到目前为止,我提出的唯一解决方法是使用execute immediate:

IF NOT EXISTS (
    SELECT 1
    FROM sysobjects
    WHERE name = 'a_table'
    AND type = 'U'
)
EXECUTE("CREATE TABLE a_table (
    col1 int not null,
    col2 int null
)")
GO

就像一个魅力,感觉就像一个肮脏的黑客。

其他提示

除了在create table

中调用execute("create table ...")之外别无他法

SYBASE手册说:

  

当在if ... else块或a中发生create table命令时   while循环,Adaptive Server之前为表创建模式   确定条件是否为真。如果这可能会导致错误   该表已存在。为了避免这种情况,要么确保a   具有相同名称的视图在数据库中尚不存在或使用   执行语句,如下:

if not exists
    (select * from sysobjects where name="my table")
begin
execute "create table mytable(x int)"
end

我没有对此进行测试,但您可以尝试将create table语句移动到sproc中。然后,您可以根据现有的if语句有条件地调用该sproc。

分配<!> quot; CREATE TABLE <!>;在char @variable中声明然后执行EXEC(@variable)。

如果您想要始终创建表格,但有条件地删除它,您可以使用:

IF(SELECT count(*) FROM sysobjects WHERE name="tableNameWithoutUserPart") > 0
    DROP TABLE tableNameWithUserPart
GO

CREATE TABLE tableNameWithUserPart ...

不需要解决方法;)

根据文件:

CREATE [ GLOBAL TEMPORARY ] TABLE [ IF NOT EXISTS ] [ owner.]table-name
( { column-definition | table-constraint | pctfree }, ... )
[ { IN | ON } dbspace-name ]
[ ENCRYPTED ]
[ ON COMMIT { DELETE | PRESERVE } ROWS
   | NOT TRANSACTIONAL ]
[ AT location-string ]
[ SHARE BY ALL ]

只需使用IF NOT EXISTS。

IF object_id('a_table') IS NULL
BEGIN
    CREATE TABLE a_table (
        col1 int not null,
        col2 int null
    ) 
END

使用 Sybase 10.01

进行测试时,此功能正常
if not exists(select * from SysColumns where tname = 'AAA') then create table DBA.AAA(  UNIQUEID integer not null ) END IF ;

尝试使用Begin和End。

如果不存在(     SELECT Count(1)     来自sysobjects     WHERE name ='a_table'     AND type ='U' ) 的 BEGIN CREATE TABLE a_table(     col1 int not null,     col2 int null ) 的 END GO

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top