简体   繁体   中英

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'.

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.

Rather try

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

Have a look at this example

SQL Fiddle DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM