Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : error creating table with multiple primary keys

Query is as follows:

create TABLE tbl_temp (
[ref] numeric(18), 
[item_code] varchar(50), 
[item_desc] nvarchar(150),
[Qty] smallint) PRIMARY KEY (ref, item_code))

Returning error:

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

like image 844
HelpASisterOut Avatar asked Dec 26 '22 03:12

HelpASisterOut


1 Answers

Try this way:

create TABLE tbl_temp 
(
   [ ref] numeric(18), 
   [item_code] varchar(50), 
   [item_desc] nvarchar(150),
   [Qty] smallint,
   PRIMARY KEY (ref, item_code)
) 

But better way to do that is to use constraint as below:

create TABLE tbl_temp 
(
   [ ref] numeric(18), 
   [item_code] varchar(50), 
   [item_desc] nvarchar(150),
   [Qty] smallint,
   CONSTRAINT pk_tbl_temp  PRIMARY KEY (ref, item_code)
) 

or

create TABLE tbl_temp 
(
   [ ref] numeric(18), 
   [item_code] varchar(50), 
   [item_desc] nvarchar(150),
   [Qty] smallint
) 

ALTER TABLE tbl_temp 
 ADD CONSTRAINT pk_tbl_temp  PRIMARY KEY (ref, item_code)

Is better way because you set a friendly name for your PK.

like image 152
Robert Avatar answered Jan 31 '23 11:01

Robert