将数据插入 table 中,其中 id 列应在不使用标识的情况下使用同一 table 中的最新 id 值递增
Insert data into table where the id column should increment with latest id value from same table without using identity
我有一个 table temp1,其中包含所有数据,现在我需要将值插入另一个 table "temp",其中 "temp" 中的 id 列应该增加一个值,因为 temp.
中还有另一个标识列
temp(id int primay key,name varchar(100),sql_identity int having identity)
temp1(name varchar(100))
当我尝试使用以下代码时
set @inc = 10
insert into temp
select (select coalesce(max(id),0) + @inc from temp), name
from temp1
我在 SQL 服务器中遇到以下错误:
Msg 2627, Level 14, State 1, Line 4
Violation of PRIMARY KEY constraint 'PK__temp__3213E83F7C06E24B'. Cannot insert duplicate key in object 'dbo.temp'. The duplicate key value is (10).
The statement has been terminated.
理想情况下,临时 table 数据应采用以下方式:
id | name
1 | val1
2 | val2
3 | val3
试试这个,你的 table temp1 有很多记录,这就是你得到这样的错误的原因。
set @inc = 10
insert into temp
(
id ,name
)
select ROW_NUMBER() OVER (ORDER BY name)+(select coalesce(max(id),0) + @inc from temp), name
from temp1
不要尝试在 SQL 中使用您自己的自动递增机制 - 它注定会失败。
相反,使用内置结构 SQL 服务器提供。
如果您在 table 上已经有一个标识列,并且您需要另一个类似标识的列,那么最好的办法是使用 sequence 并让 SQL 服务器处理编号。
创建序列:
CREATE SEQUENCE dbo.SampleSequence
START WITH 1
INCREMENT BY 10 ;
GO
并将其用作列的默认值:
CREATE TABLE dbo.Temp
(
Id int
CONSTRAINT PK_Temp PRIMARY KEY CLUSTERED
CONSTRAINT DF_Temp_Id DEFAULT (NEXT VALUE FOR dbo.SampleSequence),
name varchar(100) NOT NULL,
sql_identity int NOT NULL identity(1,1),
) ;
请注意,使用序列,就像使用标识一样,不能保证连续编号,也不能保证值的唯一性(不过,只要不加以调和,它就是唯一的)。
我有一个 table temp1,其中包含所有数据,现在我需要将值插入另一个 table "temp",其中 "temp" 中的 id 列应该增加一个值,因为 temp.
中还有另一个标识列temp(id int primay key,name varchar(100),sql_identity int having identity)
temp1(name varchar(100))
当我尝试使用以下代码时
set @inc = 10
insert into temp
select (select coalesce(max(id),0) + @inc from temp), name
from temp1
我在 SQL 服务器中遇到以下错误:
Msg 2627, Level 14, State 1, Line 4
Violation of PRIMARY KEY constraint 'PK__temp__3213E83F7C06E24B'. Cannot insert duplicate key in object 'dbo.temp'. The duplicate key value is (10).
The statement has been terminated.
理想情况下,临时 table 数据应采用以下方式:
id | name
1 | val1
2 | val2
3 | val3
试试这个,你的 table temp1 有很多记录,这就是你得到这样的错误的原因。
set @inc = 10
insert into temp
(
id ,name
)
select ROW_NUMBER() OVER (ORDER BY name)+(select coalesce(max(id),0) + @inc from temp), name
from temp1
不要尝试在 SQL 中使用您自己的自动递增机制 - 它注定会失败。
相反,使用内置结构 SQL 服务器提供。
如果您在 table 上已经有一个标识列,并且您需要另一个类似标识的列,那么最好的办法是使用 sequence 并让 SQL 服务器处理编号。
创建序列:
CREATE SEQUENCE dbo.SampleSequence
START WITH 1
INCREMENT BY 10 ;
GO
并将其用作列的默认值:
CREATE TABLE dbo.Temp
(
Id int
CONSTRAINT PK_Temp PRIMARY KEY CLUSTERED
CONSTRAINT DF_Temp_Id DEFAULT (NEXT VALUE FOR dbo.SampleSequence),
name varchar(100) NOT NULL,
sql_identity int NOT NULL identity(1,1),
) ;
请注意,使用序列,就像使用标识一样,不能保证连续编号,也不能保证值的唯一性(不过,只要不加以调和,它就是唯一的)。