SQL T-SQL Temp Tables

The below code works, but when it runs a 2nd time, the error message is generated:
"There is already an object named 'PK_UpdatesQQ' in the database."

I cannot get the constraint to drop even though the temp table is dropped.  There appears to be a unique step because it is a constraint attached to a temporary table?


CREATE TABLE [dbo].[#Temp00](
[VisitID] [int] NOT NULL,
DecisionTmForDispFromObsv varchar(24) NOT NULL DEFAULT '',
DispositionType varchar(300) NOT NULL DEFAULT '',
DischargeTo varchar(300) NOT NULL DEFAULT ''
) ON [PRIMARY]

ALTER TABLE [dbo].[#Temp00] ADD  CONSTRAINT [PK_UpdatesQQ] PRIMARY KEY CLUSTERED ( [VisitID] ASC ) WITH (IGNORE_DUP_KEY = ON) ON [PRIMARY]
dastaubAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mike EghtebasDatabase and Application DeveloperCommented:
IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.[#Temp00]'))
 BEGIN 
ALTER TABLE [#Temp00] DROP CONSTRAINT [PK_UpdatesQQ]
END

Open in new window

0
Duy PhamFreelance IT ConsultantCommented:
Try to delete the PK Constraint before dropping the table:
IF EXISTS (SELECT * FROM sys.key_constraints WHERE type = 'PK' AND parent_object_id = OBJECT_ID(N'[dbo].[#Temp00]') AND name = N'PK_UpdatesQQ')
BEGIN
    ALTER TABLE [dbo].[#Temp00] DROP CONSTRAINT [PK_UpdatesQQ]
END

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dastaubAuthor Commented:
The answer is to create a constraint without a name.  Example below.

CREATE TABLE [dbo].[#Temp00](
[VisitID] [int] NOT NULL,
DecisionTmForDispFromObsv varchar(24) NOT NULL DEFAULT '',
DispositionType varchar(300) NOT NULL DEFAULT '',
DischargeTo varchar(300) NOT NULL DEFAULT ''
PRIMARY KEY CLUSTERED ( [VisitID] ASC ) WITH (IGNORE_DUP_KEY = ON))
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.