如何仅在表不存在时创建表?使用“object_id(‘table’) IS NULL”不起作用?
我想检查该表是否不存在,然后创建一个,否则,将数据插入其中。
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 ...
第一次运行时,表已创建,但第二次运行时,sybase 抱怨该表已存在。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
原因是整个语句 - if 及其“true”部分被编译为一个。
如果表在编译期间存在 - 错误。
因此,您可以将
CREATE TABLE
语句放入动态 sql 状态中EXEC('CREATE TABLE....')
那么 Sybase 在编译时看到的就是
:
EXEC
在执行之前不会被编译,此时您知道没有表并且一切都很好。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 statemetnEXEC('CREATE TABLE....')
Then all that Sybase sees at compilation is:
The contents of
EXEC
are not compiled until execution, by when you know there's no table and all is well.