Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

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

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_table'
    AND type = 'U'
)
DROP TABLE a_table
GO

But if I try to do the same with table creation, I always get warned that the table already exists, because it went ahead and tried to create my table and ignored the conditional statement. Just try running the following statement twice, you'll see what I mean:

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

Running the above produces the following error:

SQL Server Error on (localhost) Error:2714 at Line:7 Message:There is already an object named 'a_table' in the database.

What's the deal with that?!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...