How do I conditionally create a table in Sybase (TSQL)?

前端 未结 9 1760
有刺的猬
有刺的猬 2020-12-14 20:31

OK, so Sybase (12.5.4) will let me do the following to DROP a table if it already exists:

IF EXISTS (
    SELECT 1
    FROM sysobjects
    WHERE name = \'a_t         


        
相关标签:
9条回答
  • 2020-12-14 20:57

    There is no other way than calling create table in execute("create table ...")

    SYBASE Manual says:

    When a create table command occurs within an if...else block or a while loop, Adaptive Server creates the schema for the table before determining whether the condition is true. This may lead to errors if the table already exists. To avoid this situation, either make sure a view with the same name does not already exist in the database or use an execute statement, as follows:

    if not exists
        (select * from sysobjects where name="my table")
    begin
    execute "create table mytable(x int)"
    end
    
    0 讨论(0)
  • 2020-12-14 20:57

    Try using Begin and End.

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

    0 讨论(0)
  • 2020-12-14 20:59
    IF object_id('a_table') IS NULL
    BEGIN
        CREATE TABLE a_table (
            col1 int not null,
            col2 int null
        ) 
    END
    
    0 讨论(0)
  • 2020-12-14 20:59

    This works when tested with Sybase anywhere 10.01 :

    if not exists(select * from SysColumns where tname = 'AAA') then create table DBA.AAA(  UNIQUEID integer not null ) END IF ;
    
    0 讨论(0)
  • 2020-12-14 21:03

    If you want to always create the table, but conditionally drop it, you can use:

    IF(SELECT count(*) FROM sysobjects WHERE name="tableNameWithoutUserPart") > 0
        DROP TABLE tableNameWithUserPart
    GO
    
    CREATE TABLE tableNameWithUserPart ...
    
    0 讨论(0)
  • 2020-12-14 21:12

    The only workaround I've come up with so far is to use 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
    

    works like a charm, feels like a dirty hack.

    0 讨论(0)
提交回复
热议问题