SQL Server - Create temp table if doesn't exist

做~自己de王妃 提交于 2020-01-23 11:35:05

问题


In my SQL Server 2012 environment, I've created a series of stored procedures that pass pre-existing temporary tables among themselves (I have tried different architectures here, but wasn't able to bypass this due to the nature of the requirements / procedures).

What I'm trying to do is to, within a stored procedure check if a temporary table has already been created and, if not, to create it.

My current SQL looks as follows:

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

But when I try and run it when the table already exists, I get the error message

There is already an object named '#MyTable' in the database

So it seems it doesn't simply ignore those lines within the If statement.

Is there a way to accomplish this - create a temp table if it doesn't already exist, otherwise, use the one already in memory?

Thanks!

UPDATE:

For whatever reason, following @RaduGheorghiu's suggestion from the comments, I found out that the system creates a temporary table with a name along the lines of dbo.#MyTable________________________________________________0000000001B1

Is that why I can't find it? Is there any way to change that? This is new to me....


回答1:


Following the link here, http://weblogs.sqlteam.com/mladenp/archive/2008/08/21/SQL-Server-2005-temporary-tables-bug-feature-or-expected-behavior.aspx

It seems as though you need to use the GO statement.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/42511328/sql-server-create-temp-table-if-doesnt-exist

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