我有以下查询:
IF NOT EXISTS (SELECT 1
FROM sysobjects
WHERE id = Object_id('tempdb..TEMP_THETH_DETAILS'))
EXECUTE (
'CREATE TABLE tempdb..TEMP_THETH_DETAILS( THETH_ID NUMERIC(5) NOT NULL, LANGUAGE VARCHAR(3) DEFAULT ''EN'' NOT NULL)'
)
GO
问题是检查,似乎tempdb不考虑如果不存在,可能是因为表是在tempdb中创建的。
所以我的问题是有一种方法我可以检查临时表是否存在?
试试这个:
IF object_id('tempdb..TEMP_THETH_DETAILS') is null
begin
EXECUTE
(
'CREATE TABLE tempdb..TEMP_THETH_DETAILS
( THETH_ID NUMERIC(5) NOT NULL,
LANGUAGE VARCHAR(3) DEFAULT ''EN'' NOT NULL
)'
)
end
go
可以在检查表是否存在时捕获异常,并在异常被截获时执行代码。
在Sybase:begin
declare SQLE_TABLE_NOT_FOUND EXCEPTION FOR SQLSTATE '42W33';
...
if exists(select 'x
from #tmpTable) then
-- TODO
endif;
-- at the end of the function if table not exists,
-- thrown exception is catched here
exception when SQLE_TABLE_NOT_FOUND then
-- TODO
end;
use tempdb
GO
IF NOT EXISTS (SELECT 1
FROM sysobjects
WHERE id = Object_id('tempdb..TEMP_THETH_DETAILS'))
EXECUTE (
'CREATE TABLE tempdb..TEMP_THETH_DETAILS( THETH_ID NUMERIC(5) NOT NULL,
LANGUAGE VARCHAR(3) DEFAULT ''EN'' NOT NULL)'
)
GO