a) 检查一个表以找到需要创建的其他表的名称 b) 检查该表是否已经存在 c) 如果没有,创建它 d) 用新数据填满她
现在,这一切都可以正常工作,直到必须检查表是否存在的部分:
set @NewTablename = (select NAME from SomeTable where ID= @i)
set @Tabelexists = 'select case when exists(select * from sys.tables where name = ''' + @NewTabelname + ''') then 1 else 0 end'
declare @check as int execute(@Tabelexists)
IF @check is NULL
BEGIN
Create Table
END
ELSE
BEGIN
execute('Delete from '+ @NewTableName)
END
<other stuff like inserts and so on)
但不知何故,当表不存在时,@check 似乎总是为 NULL,如果存在,则为 1。
如果我检查 IF @check is null
如果表不存在,则只执行 TRUE 部分。如果它确实在那一刻存在没有被执行......
如果我检查 IF @check =1
只执行 ELSE
@check 的值显然总是 NULL 或 1 或 0............
我在这里不知所措! 如何检查使用变量作为表名的表是否存在?
达米安,我明白你在说什么。但是如果我这样做我仍然没有结果我可以测试:
声明@check as int execute ('select case when exists(select * from sys.tables where name = ''' + @Tabelnaam + ''') then 1 else 0 end')
最佳答案
你可以这样检查
if not exists(select * from sys.tables where type='u' and name = @NewTabelname )
BEGIN
Create Table
END
ELSE
BEGIN
execute('Delete from '+ @NewTableName)
END
关于sql - 如何使用变量作为表名检查表是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12457363/