There Is Already an Object Named '#Result' in the Database

Temporary table in SQL server causing ' There is already an object named' error

You are dropping it, then creating it, then trying to create it again by using SELECT INTO. Change to:

DROP TABLE #TMPGUARDIAN
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))

INSERT INTO #TMPGUARDIAN
SELECT LAST_NAME,FRST_NAME
FROM TBL_PEOPLE

In MS SQL Server you can create a table without a CREATE TABLE statement by using SELECT INTO

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

A temp table lives for the entirety of the current session. If you run this statement more than once, then the table will already be there. Either detect that and truncate it, or before selecting into it drop it if it exists:

DROP TABLE IF EXISTS #tmpUnidadesPresupuestadas

If prior to SQL Server 2016, then you drop as such:

IF OBJECT_ID('tempdb.dbo.#tmpUnidadesPresupuestadas', 'U') IS NOT NULL
DROP TABLE #tmpUnidadesPresupuestadas;

SQL Error: There is already an object named 'TPatients' in the database

The issue is because you are giving your constraints the same name as the table.

Give them a unique name, eg prefix with "PK_Tpatients" if it's a primary key.

Note that tables and constraints are all "objects" and as such need unique names.

ERROR: There is already an object named '#temp' in the database

Like Larnu already said, this is a parsing error. It sees you trying to create the same table multiple times and doesn't know that only one of them can be reached.

Depending on how this temp table is being used there might be better ways to refactor the code but working from what was provided you have a couple of options:

  1. Use dynamic queries to hide the SQL from the parser. Dynamic queries are generally frowned upon and should be avoided when possible. (This has been updated to use a global temp table to work around the scope issue)
IF 1=1
EXEC('SELECT
[col1] = ''inside IF 1'',
[col2] = ''inside IF 2''
INTO
##temptable')
ELSE
EXEC('SELECT
[col1] = ''inside Else 1'',
[col2] = ''inside Else 2'',
[col3] = ''inside Else 3''
INTO
##temptable')

  1. If you know ahead of time all of the column names then you can CREATE the #temptable with all possible columns, and in your conditional logic you can use ALTER TABLE to remove unused columns.
CREATE TABLE #temptable (
col1 varchar(10),
col2 varchar(10),
col3 varchar(10)
)

IF 1 = 1
BEGIN
INSERT INTO #temptable (col1, col2)
SELECT
col1 = 'inside IF 1',
col2 = 'inside IF 2'

ALTER TABLE #temptable DROP COLUMN col3
END
ELSE
BEGIN
INSERT INTO #temptable (col1, col2, col3)
SELECT
col1 = 'inside Else 1',
col2 = 'inside Else 2',
col3 = 'inside Else 3'
END


Related Topics



Leave a reply



Submit