I have the following query
declare @var1 int, @var2 int
set @var1 = 110
set @var2 = 300
IF object_id('tempdb..#tbl_Contract') IS NOT NULL
BEGIN
ALTER TABLE #tbl_Contract drop constraint PK_#tbl_Contract
DROP TABLE #tbl_Contract
END
CREATE TABLE #tbl_Contract
( ContractID int NOT NULL
, PersonID int NOT NULL
, EndDate smalldatetime NULL
, CONSTRAINT [PK_#tbl_Contract] PRIMARY KEY CLUSTERED
(
ContractID ASC
)
)
...
But when I run this query the second time I'm getting an error:
Msg 2714, Level 16, State 5, Line 1 There is already an object named 'PK_#tbl_Contract' in the database. Msg 1750, Level 16, State 0, Line 1 Could not create constraint. See previous errors.
What I'm doing wrong? Why my primary key was not removed?
Should I use GO
after ALTER
? But I can't because there are some varibles
You don't need to drop a constraint and then immediately drop the table. It is simpler to just drop the table. Also, there really is no need to name constraints in a temp table. You can greatly simplify your code like this.
IF object_id('tempdb..#tbl_Contract') IS NOT NULL
BEGIN
DROP TABLE #tbl_Contract
END
GO
CREATE TABLE #tbl_Contract
( ContractID int NOT NULL PRIMARY KEY CLUSTERED
, PersonID int NOT NULL
, EndDate smalldatetime NULL
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With