Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composite Primary Key On Table Variable In Stored Procedure

I'm new to stored procedures and trying to add a composite primary key to a table variable.

DECLARE @statistictemp TABLE (     MajorName      VARCHAR(50) NOT NULL,      SubName       VARCHAR(50) NOT NULL,      DetailedName   VARCHAR(50) NOT NULL,      UniversityID   SMALLINT    NOT NULL,      StatisticValue DECIMAL(9,3) );  ALTER TABLE @statistictemp  ADD CONSTRAINT pk_statistictemp  PRIMARY KEY (MajorName, SubName, DetailedName, UniversityID); 

I'm getting an error on ALTER TABLE @statistictemp saying

Incorrect syntax near '@statistictemp'. Expecting ID, QUOTED_ID, or '.'.

What am I doing wrong here? How do you add a composite primary key to a table variable?

like image 671
Greg Avatar asked Feb 17 '12 05:02

Greg


People also ask

Can we create primary key on table variable in SQL Server?

Table variables allow us to create the following constraints: Primary Key. Unique.

Can a table have composite primary key?

A Composite Primary Key is created by combining two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined, but it does not guarantee uniqueness when taken individually, or it can also be understood as a primary key created by combining two or more ...

How do you set a primary key variable in SQL?

You can create a primary key in SQL Server (Transact-SQL) with the ALTER TABLE statement. However, you can only use the ALTER TABLE statement to create a primary key on column(s) that are already defined as NOT NULL.


1 Answers

You can do it like this:

DECLARE @statistictemp TABLE (     MajorName       VARCHAR(50) NOT NULL,      SubName        VARCHAR(50) NOT NULL,      DetailedName    VARCHAR(50) NOT NULL,      UniversityID    SMALLINT NOT NULL,      StatisticValue  DECIMAL(9,3),     PRIMARY KEY (MajorName, SubName, DetailedName, UniversityID) ); 

You can test that the primary key constraint works by trying to insert duplicates: e.g.,

INSERT INTO @statistictemp(MajorName, SubName, DetailedName, UniversityID) SELECT 'a','b','c',1 INSERT INTO @statistictemp(MajorName, SubName, DetailedName, UniversityID) SELECT 'a','b','c',1 

The second statement will throw an error:

Msg 2627, Level 14, State 1, Line 13
Violation of PRIMARY KEY constraint 'PK_#1EA48E8_B595483D208CD6FA'. Cannot insert duplicate key in object 'dbo.@statistictemp'.
The statement has been terminated.

like image 168
Steven Schroeder Avatar answered Oct 08 '22 16:10

Steven Schroeder