How to only create table if it doesn't exist? Using “object_id('table') IS NULL” doesn't work?

爷,独闯天下 提交于 2019-12-10 15:54:47

问题


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.



来源:https://stackoverflow.com/questions/7974541/how-to-only-create-table-if-it-doesnt-exist-using-object-idtable-is-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!