在SQL Server中,可以通過以下幾種方式設置主鍵自增長:
IDENTITY(1,1)
,表示該列是自增長的。示例代碼如下: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;
以上是三種設置主鍵自增長的方式,你可以根據具體的需求選擇適合的方式來實現。