Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compound primary key in Table type variable

SQL Server 2008:

DECLARE @MyTable TABLE(     PersonID INT NOT NULL,     Person2ID INT NOT NULL,     Description NVARCHAR(100), CONSTRAINT PK PRIMARY KEY CLUSTERED (PersonID, Person2ID) ); 

Gives:

Msg 156, Level 15, State 1, Line 5 Incorrect syntax near the keyword 'CONSTRAINT'. 

Is there any way to have compound Primary key in Table valued variables?

like image 873
pkario Avatar asked Sep 14 '09 11:09

pkario


People also ask

Can a primary key be a compound key?

Primary keys must contain unique values. A primary key column cannot have NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key.

Can we create primary key in table variable?

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

Which datatype is used to set primary key in a table?

Good practice for primary keys in tables Prefer a numeric type because numeric types are stored in a much more compact format than character formats.

What is a compound primary key in SQL?

What Is a Composite Key in SQL? A composite key in SQL can be defined as a combination of multiple columns, and these columns are used to identify all the rows that are involved uniquely. Even though a single column can't identify any row uniquely, a combination of over one column can uniquely identify any record.


1 Answers

You can define a composite primary key like this:

DECLARE @MyTable TABLE (        PersonID INT NOT NULL,         Person2ID INT NOT NULL,         Description NVARCHAR(100),     PRIMARY KEY (PersonID, Person2ID) ); 
like image 69
Mitch Wheat Avatar answered Sep 27 '22 23:09

Mitch Wheat