简体   繁体   English

SQL Server:错误创建具有多个主键的表

[英]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'. 消息156,级别15,状态1,行1关键字'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: 但更好的方法是使用如下constraint

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设置一个友好的名字。

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 SQL Fiddle DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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