SQL Server - Create temp table if doesn't exist

£可爱£侵袭症+ 提交于 2019-12-06 01:16:42

Try wrapping your actions in a begin...end block:

if object_id('tempdb..#MyTable') is null
begin
  create table #MyTable (
     Col1 int
   , Col2 varchar(10)
  );
end

You meant to use IS NOT NULL i think... this is commonly used to clear temp tables so you don't get the error you mentioned in your OP.

IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP TABLE #MyTable
CREATE TABLE #MyTable
(
    Col1 INT,
    Col2 VARCHAR(10)
);

The big difference is the DROP TABLE statement after you do your logical check. Also, creating your table without filling data doesn't make it NULL

DROP TABLE #MyTable

CREATE TABLE #MyTable
(
    Col1 INT,
    Col2 VARCHAR(10)
);

IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL 
SELECT 1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!