How to only create table if it doesn't exist?

2019-06-28 03:19发布

问题:

I would like to check if the table does not exist, then create one, otherwise, insert data into it.

use tempdb
if object_id('guest.my_tmpTable') IS NULL 
begin
   CREATE TABLE guest.my_tmpTable (
    id int,
    col1 varchar(100)
   )
end 

--- do insert here ...

The first time run, the table was created but the 2nd run the sybase complains the table already exist.

Thanks!

回答1:

The reason is that the entire statement - if and its "true" part are compiled as one.

If the table exists during compilation - error.

So you could put the CREATE TABLE statement into a dynamic sql statemetn EXEC('CREATE TABLE....')

Then all that Sybase sees at compilation is:

IF object_id('mytab') IS NULL
  EXEC('something or other')

The contents of EXEC are not compiled until execution, by when you know there's no table and all is well.



标签: sybase