在SQL Server中,可以通過(guò)以下幾種方式設(shè)置主鍵自增長(zhǎng):
IDENTITY(1,1)
,表示該列是自增長(zhǎng)的。示例代碼如下:CREATE TABLE TableName (
ID INT IDENTITY(1,1) PRIMARY KEY,
Column1 datatype1,
Column2 datatype2,
...
);
CREATE SEQUENCE SequenceName
AS INT
START WITH 1
INCREMENT BY 1
MINVALUE 1
NO MAXVALUE
NO CYCLE;
CREATE TABLE TableName (
ID INT DEFAULT NEXT VALUE FOR SequenceName PRIMARY KEY,
Column1 datatype1,
Column2 datatype2,
...
);
CREATE TABLE TableName (
ID INT PRIMARY KEY,
Column1 datatype1,
Column2 datatype2,
...
);
CREATE TRIGGER TriggerName
ON TableName
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO TableName (ID, Column1, Column2, ...)
SELECT NEXT VALUE FOR SequenceName, Column1, Column2, ...
FROM inserted;
END;
以上是三種設(shè)置主鍵自增長(zhǎng)的方式,你可以根據(jù)具體的需求選擇適合的方式來(lái)實(shí)現(xiàn)。