SQL Server:使用多个主键创建表时出错

时间:2021-06-03 11:29:25

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

Msg 156,第15级,状态1,第1行错误的语法靠近关键字“主”。

2 个解决方案

#1


6  

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.

这样更好,因为您为您的PK设置了一个友好的名称。

#2


0  

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

#1


6  

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.

这样更好,因为您为您的PK设置了一个友好的名称。

#2


0  

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