好的,所以 Sybase (12.5.4) 会让我执行以下操作来删除已经存在的表:
IF EXISTS (
SELECT 1
FROM sysobjects
WHERE name = 'a_table'
AND type = 'U'
)
DROP TABLE a_table
GO
但是如果我尝试对表创建做同样的事情,我总是会收到警告说该表已经存在,因为它继续尝试创建我的表并忽略了条件语句。只需尝试运行以下语句两次,您就会明白我的意思:
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
运行上面会产生以下错误:
SQL Server Error on (localhost) Error:2714 at Line:7 Message:There is already an object named 'a_table' in the database.
这有什么关系?!
最佳答案
到目前为止,我想出的唯一解决方法是使用立即执行:
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
就像一个魅力,感觉就像一个肮脏的黑客。
关于tsql - 如何有条件地在 Sybase (SQL) 中创建表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/307942/