繁体   English   中英

更新一个表中的一行并在另一个表中创建一个新行以满足外键关系

[英]Update a row in one table and also creating a new row in another table to satisfy a foreign key relationship

我有一个更新 Star 类型的存储过程。 数据库表starValList 有一个名为galaxyValList 的表的外键。 该键是galaxyID。

因此,如果为空或空 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 表!

但我认为它也因为这个错误而失败:

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_starValList_galaxyValList". The conflict occurred in database "Astro105", table "dbo.galaxyValList", column 'galaxyID'.

它失败是因为在galaxyValList 表中可能还没有该特定星系的条目。

但是我仍然需要galaxyValList 中的行,因为它可以在以后使用。

如何修复我的存储过程,使其不会产生此错误?

谢谢!

使用if exists检查表中if exists该值。 如果是,则进行更新。 如果它没有,那么可能有一些其他逻辑来创建它或任何您的要求,以便可以在更新中使用该值。 下面的基本示例:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM