【问题标题】:Update a row in one table and also creating a new row in another table to satisfy a foreign key relationship更新一个表中的一行并在另一个表中创建一个新行以满足外键关系
【发布时间】:2020-12-28 02:26:52
【问题描述】:

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

所以我需要创建一个新的 GalaxyID 值,如果它是 null 或空 GUID。

所以我试试这个:

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中的行,因为它可以稍后使用。

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

谢谢!

【问题讨论】:

  • 通过从您的表dbo.galaxyValList 中获取正确的值。将NEWID 用于表starValListgalaxyID 的值实际上有100% 的机会生成galaxyValList 中不存在的值
  • 旁注,一年多来,SQL Server 2008 完全不受支持,您应该尽快查看升级路径。

标签: sql-server tsql sql-server-2008


【解决方案1】:

使用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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多