在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;
以上是三种设置主键自增长的方式,你可以根据具体的需求选择适合的方式来实现。