Cod*_*key 4 variables insert sql-server-2008
我有一个带有主键的表event_id
。我需要将Plant
from更改IM17
为SG18
.
我不想删除行(由于历史原因而保留)。执行以下 SQL 时出现 PK 违规。
DECLARE @plant CHAR(4)
DECLARE @l_event_id INT
SELECT @plant = 'SG18'
SET @l_event_id = (SELECT MAX(cast(event_id as int)) FROM dbo.event_header)
INSERT INTO dbo.event_header (
event_id, scenario_name, actor_code, method_code,
SAP_plant_code, object_id,serial_no
)
SELECT @l_event_id + 1 , eh.scenario_name, eh.actor_code,
eh.method_code, @plant, eh.object_id, eh.serial_no
FROM dbo.event_header eh
WHERE eh.SAP_plant_code = 'IM17';
Run Code Online (Sandbox Code Playgroud)
您的方法不起作用,因为您MAX(cast(event_id as int))
只评估一次 - 然后尝试插入所有 n 具有相同值的新行event_id
...
你需要使用这样的东西来完成你的工作:
DECLARE @plant CHAR(4) = 'SG18'
DECLARE @l_event_id INT
SELECT @l_event_id = MAX(CAST(event_id AS INT)) FROM dbo.event_header)
;WITH CTE AS
(
SELECT
eh.scenario_name,
eh.actor_code,
eh.method_code,
eh.object_id,
eh.serial_no,
RowNum = ROW_NUMBER() OVER (ORDER BY eh.serial_no)
FROM dbo.event_header eh
WHERE eh.SAP_plant_code = 'IM17';
)
INSERT INTO
dbo.event_header (event_id, scenario_name, actor_code, method_code, SAP_plant_code, object_id,serial_no)
SELECT
@l_event_id + RowNum,
scenario_name, actor_code, method_code,
@plant,
object_id, serial_no
FROM
CTE
Run Code Online (Sandbox Code Playgroud)
基本上,这个 CTE(公用表表达式)获取您需要的所有值,此外它还用于ROW_NUMBER()
生成序列号(从 1 到为 选择的行数@plant = 'IM17'
)。
当您将其添加RowNum
到先前的最大值时,并且现在没有其他数据插入到该目标表中 - 那么您就有成功的机会!