我在SAP Interactive SQL(Sybase)中有以下if-else语句:
IF EXISTS (SELECT 1 FROM sysobjects o, sysusers u WHERE o.uid=u.uid AND o.name = 'mytable' AND u.name = 'user1')
BEGIN
PRINT "Dropping table mytable"
DROP TABLE mytable
PRINT "Dropped table mytable"
END
ELSE
BEGIN
PRINT "Table mytable does not exist"
SELECT * INTO mytable FROM mytable2
PRINT "Table mytable copied from mytable2"
END
错误讯息:
"Could not execute statement. There is already an object named named 'mytable' in the database."
如果我删除了else子句,它会检查该表,如果存在,则会按预期删除它。但是与else子句一起,它选择最后一个是否存在原始表。因此表已存在的错误消息。这里有什么问题?我认为我的语法正确(取自sybase文档和其他来源)。
答案 0 :(得分:1)
试试这个:
IF OBJECT_ID("mytable") IS NOT NULL
DROP TABLE mytable
GO
SELECT * INTO mytable FROM mytable2
EDIT1:
IF OBJECT_ID("mytable") IS NOT NULL
DROP TABLE mytable
EXEC ("select * INTO mytable FROM mytable2")
答案 1 :(得分:0)
此处的情况是mytable
用户所有者不是'user1'
。因此,执行来自ELSE
块的代码,并且因为mytable
仍然存在,它将失败。尝试:
IF EXISTS (SELECT 1 FROM sysobjects o WHERE o.name = 'mytable' AND o.type = 'U')
和
EXEC('DROP TABLE mytable')
您还可以按照不同的方式进行条件删除:
if (object_id('mytable') is not null)
EXEC('drop table mytable')