如何设置主键?

时间:2019-02-11 14:09:50

标签: sql sql-server primary-key

SELECT TOP 1000 [LicensePlate]
      ,[Manufacturer]
      ,[Model]
      ,[Colour]
      ,[Year]
      ,[EngineSize]
      ,[Value]
  FROM [Cars2].[dbo].[Cartable1]

以上是我在汽车桌子上的布局。我对SQL完全陌生,想知道如何将“牌照”设置为主键?

4 个答案:

答案 0 :(得分:4)

CREATE TABLE Cartable1(
    LicensePlate int NOT NULL PRIMARY KEY,
    Manufacturer varchar(255) NOT NULL,
    Model varchar(255),
    Colour varchar(255),
    Model varchar(255),
    Year int,
    EngineSize int,
    Value float
);

答案 1 :(得分:4)

首先按该列查找任何重复项。

SELECT
    C.LicensePlate,
    AmountDuplicates = COUNT(*)
FROM
    Cars2.dbo.Cartable1 AS C
GROUP BY
    C.LicensePlate
HAVING
    COUNT(*) > 1

如果出现任何记录,则需要删除所有重复项或更新其车牌,以使它们不再重复。

您还需要检查NULL值并更新或删除它们(主键不能为null)。

SELECT
    C.*
FROM
    Cars2.dbo.Cartable1 AS C
WHERE
    C.LicensePlate IS NULL

然后您可以使用以下命令添加PRIMARY KEY约束:

ALTER TABLE Cars2.dbo.Cartable1 
    ADD CONSTRAINT PK_Cartable1 -- Name of the constraint
    PRIMARY KEY (LicensePlate)

如果LicensePlate可以容纳NULL个值,则可能会出错。您可以使用ALTER TABLE进行更改:

ALTER TABLE Cars2.dbo.Cartable1 ALTER COLUMN LicensePlate VARCHAR(20) NOT NULL -- The proper data type

如果您已经在该表上定义了主键,则必须将其删除然后创建新的主键(一个表一次只能具有1个主键约束)。您可以通过以下查询检查是哪一个:

USE Cars2; -- The database name here

DECLARE @TableName VARCHAR(100) = 'Cartable1'
DECLARE @SchemaName VARCHAR(100) = 'dbo'

SELECT 
    ColumnName = Col.Column_Name,
    ConstraintName = tab.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS Tab
    INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS Col ON
        Col.Constraint_Name = Tab.Constraint_Name AND 
        Col.Table_Name = Tab.Table_Name
WHERE 
    Constraint_Type = 'PRIMARY KEY' AND 
    Col.Table_Name = @TableName AND
    Col.TABLE_SCHEMA = @SchemaName

看到结果后,可以使用另一个ALTER TABLE删除当前主键:

ALTER TABLE Cars2.dbo.Cartable1 DROP CONSTRAINT ConstraintNameFromThePreviousQuery

答案 2 :(得分:1)

在创建表或通过alter table语句时执行此操作:

create table [Cars2].[dbo].[Cartable1] (
    LicensePlace varchar(?) primary key,
    . . . 
);

我建议在创建表时以及向表中添加任何数据之前添加主键。

答案 3 :(得分:1)

If You already have table with data try this ,


 ALTER TABLE [Cars2].[dbo].[Cartable1]
        ADD CONSTRAINT PRIMARY_KEY_LicensePlate PRIMARY KEY(LicensePlate)