Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 检查两列的外键_Sql_Database_Tsql - Fatal编程技术网

Sql 检查两列的外键

Sql 检查两列的外键,sql,database,tsql,Sql,Database,Tsql,我的两个表的两列之间有一个外键。问题是,我也有一个“删除”栏,我认为记录被删除,如果它被设置为真从我的UI。所以我的外键必须检查列是否也设置为true或false 有没有办法做到这一点?我需要创建这样的规则:“如果第一个表上有任何相关记录,则不允许将第二个表的已删除列设置为false。” 如果上面的内容有点太复杂,下面是一个很长的解释: **Customer** **StatusType** Id Id Name StatusName

我的两个表的两列之间有一个外键。问题是,我也有一个“删除”栏,我认为记录被删除,如果它被设置为真从我的UI。所以我的外键必须检查列是否也设置为true或false

有没有办法做到这一点?我需要创建这样的规则:“如果第一个表上有任何相关记录,则不允许将第二个表的已删除列设置为false。”

如果上面的内容有点太复杂,下面是一个很长的解释:

**Customer**      **StatusType**
Id               Id
Name             StatusName
Surname          Deleted
StatusId
Deleted
如您所见,我有两个表,Customer表的“StatusId”包含StatusType中的主键。所以我分配了一个外键来将它们固定在一起

在我的界面中,我从不从数据库中删除任何数据,我只是将“已删除”列设置为“真”。我只在删除的列上显示设置为“false”的数据


所以问题是:如果Customer表上有相关的Customer.StatusId-StatusType.Id记录,我的外键不能允许StatusType表的“deleted”列设置为“false”。

您可以使用触发器:

create trigger trg_upd_status before update on StatusType
for each row begin
    declare customer_count int;
    if new.Deleted = 'true' then
        select count(*)
        into   customer_count
        from   Customer
        where  Deleted = 'false';
        if (customer_count > 0) then
            signal sqlstate '45001' 
            set message_text = "Not allowed to delete this record";
        end if;
    end if;
end;
/
这假设已删除列的数据类型是
varchar
,但如果是数字或稍微

请注意,这仅检查是否存在未删除的
客户
记录。因此,这意味着您还必须执行相反的操作:如果取消删除
Customer
记录,则相应的
StatusType
记录不应处于删除状态。如果更新
客户
记录并更改
状态ID
,则相同。这将是
Customer
表上的一个触发器…

试试这个

update StatusType  set Deleted='false'
 where(select count (id) from customer where deleted='true' and StatusType.id=StatusId )=0

已删除列的数据类型是什么?瓦查尔?Bit?只需为
'delete'
列创建一个
UPDATE
触发器,并验证是否存在相关字段,在这种情况下,取消更新并捕获应用程序上的错误,除非有某种自动方法,否则这可能是最好的答案。我会等几天再决定。谢谢