更新一个 table 中的一行并在另一个 table 中创建一个新行以满足外键关系
Update a row in one table and also creating a new row in another table to satisfy a foreign key relationship
我有一个更新星型类型的存储过程。数据库 table、starValList 有一个 table 的外键,名为 galaxyValList。该密钥是 galaxyID。
所以如果 galaxyID 为 null 或空 GUID,我需要创建一个新的 galaxyID 值。
所以我试试这个:
IF(@galaxyID IS NULL OR @galaxyID = '00000000-0000-0000-0000-000000000000')
BEGIN
SELECT @galaxyID=NEWID()
END
UPDATE starValList SET
[starIRR]= @starIRR,
[starDesc] = @starDesc,
[starType] = @starType,
[galaxyID]=@galaxyID
WHERE [starID] = @starID;
它适用于 starValList table!
但我认为它也因为这个错误而失败了:
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_starValList_galaxyValList". The conflict occurred in database "Astro105", table "dbo.galaxyValList", column 'galaxyID'.
它失败了,因为在 galaxyValList table.
中可能还没有该特定星系的条目
但我仍然需要 galaxyValList 中的行,因为它可以稍后使用。
如何修复我的存储过程以使其不再生成此错误?
谢谢!
使用if exists
检查值是否存在于table上。如果是,则进行更新。如果它没有,则可能有一些其他逻辑来创建它或任何您的要求,以便可以在更新中使用该值。下面的基本示例:
IF(@galaxyID IS NULL OR @galaxyID = '00000000-0000-0000-0000-000000000000')
BEGIN
SELECT @galaxyID=NEWID()
END
if not exists ( select top 1 1 from galaxyTable where galaxyId = @galaxyId)
begin
-- the @galaxyId doesnt exist, create it so you can use the value in an update later
insert into galaxyTable ( galaxyId ) select @galaxyId
end
UPDATE starValList SET
[starIRR]= @starIRR,
[starDesc] = @starDesc,
[starType] = @starType,
[galaxyID]=@galaxyID
WHERE [starID] = @starID;
我有一个更新星型类型的存储过程。数据库 table、starValList 有一个 table 的外键,名为 galaxyValList。该密钥是 galaxyID。
所以如果 galaxyID 为 null 或空 GUID,我需要创建一个新的 galaxyID 值。
所以我试试这个:
IF(@galaxyID IS NULL OR @galaxyID = '00000000-0000-0000-0000-000000000000')
BEGIN
SELECT @galaxyID=NEWID()
END
UPDATE starValList SET
[starIRR]= @starIRR,
[starDesc] = @starDesc,
[starType] = @starType,
[galaxyID]=@galaxyID
WHERE [starID] = @starID;
它适用于 starValList table!
但我认为它也因为这个错误而失败了:
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_starValList_galaxyValList". The conflict occurred in database "Astro105", table "dbo.galaxyValList", column 'galaxyID'.
它失败了,因为在 galaxyValList table.
中可能还没有该特定星系的条目但我仍然需要 galaxyValList 中的行,因为它可以稍后使用。
如何修复我的存储过程以使其不再生成此错误?
谢谢!
使用if exists
检查值是否存在于table上。如果是,则进行更新。如果它没有,则可能有一些其他逻辑来创建它或任何您的要求,以便可以在更新中使用该值。下面的基本示例:
IF(@galaxyID IS NULL OR @galaxyID = '00000000-0000-0000-0000-000000000000')
BEGIN
SELECT @galaxyID=NEWID()
END
if not exists ( select top 1 1 from galaxyTable where galaxyId = @galaxyId)
begin
-- the @galaxyId doesnt exist, create it so you can use the value in an update later
insert into galaxyTable ( galaxyId ) select @galaxyId
end
UPDATE starValList SET
[starIRR]= @starIRR,
[starDesc] = @starDesc,
[starType] = @starType,
[galaxyID]=@galaxyID
WHERE [starID] = @starID;