如何仅在表不存在时创建表?使用“object_id(‘table’) IS NULL”不起作用?

发布于 2024-12-13 10:46:53 字数 283 浏览 4 评论 0原文

我想检查该表是否不存在,然后创建一个,否则,将数据插入其中。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

咿呀咿呀哟 2024-12-20 10:46:53

原因是整个语句 - if 及其“true”部分被编译为一个。

如果表在编译期间存在 - 错误。

因此,您可以将 CREATE TABLE 语句放入动态 sql 状态中 EXEC('CREATE TABLE....')

那么 Sybase 在编译时看到的就是

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

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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文