【问题标题】:How to define referential-integrity in this scenario for 2 SQL Server tables?如何在这种情况下为 2 个 SQL Server 表定义参照完整性?
【发布时间】:2011-06-19 09:44:53
【问题描述】:

我在 SQL Server 2005 中有 2 个表,如下所示

表 A

  • ActionID(PK,int,非空)
  • ProgressID(唯一标识符,非空)
  • ReferID(唯一标识符,非空)
  • 字段 XYZ(varchar(50),非空)
  • 字段 MNO(tinyint,非 null)

表 B

  • TrackID(PK,int,非空)
  • ProgressID(唯一标识符,非空)
  • ReferID(唯一标识符,非空)
  • 字段 ABC(varchar(20),非空)
  • 字段 EFG(日期时间,非空)

现在我有一个具体的问题:

两个表中的ProgressID 指的是同一个实体。并且我想建立一个完整的关系,以便当表 B 中存在值时,无法删除表 A 中的 ProgressID。如何做到这一点?

【问题讨论】:

    标签: sql-server tsql database-design foreign-key-relationship referential-integrity


    【解决方案1】:

    我会为此推荐一个删除前触发器。类似的东西

    create trigger tr_tableA_progressId
    on TableA for Delete
    as 
        if exists
            (select 'true'
            from dbo.TableB
            where TableB.progressID = (select progressID
                                      from deleted d))
    
            BEGIN
                RAISERROR 'Cannot delete progressId exists in TableB'
                ROLLBACK TRAN
            End
    

    我不知道会强制执行您想要的约束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 2020-07-07
      • 1970-01-01
      • 2011-08-08
      相关资源
      最近更新 更多