Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.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_Sql Server_Sql Server 2008 R2 - Fatal编程技术网

Sql 查找父行的更好方法是是否可删除

Sql 查找父行的更好方法是是否可删除,sql,sql-server,sql-server-2008-r2,Sql,Sql Server,Sql Server 2008 R2,我有 父表 PId - int PDescription - varchar CId - Int CDetails - Varchar PId - Int -- Mapped from Parent ChildTable PId - int PDescription - varchar CId - Int CDetails - Varchar PId - Int -- Mapped from Parent 我需要在加载数据本身时

我有

父表

 PId - int    
 PDescription - varchar
CId - Int    
CDetails - Varchar    
PId - Int --  Mapped from Parent
ChildTable

 PId - int    
 PDescription - varchar
CId - Int    
CDetails - Varchar    
PId - Int --  Mapped from Parent
我需要在加载数据本身时确定父行是否可删除,因为我不想允许用户使用映射删除数据。下面是我的问题

select P.PId,Pdescription,Cast(Count(C.CId) as Bit)^1 "IsDeletable" 
From  ParentTable P
LEFT JOIN ChildTable C On P.Pid=C.Pid
Group By P.PId,Pdescription

这里的问题是Child有很多行,执行查询花费了很多时间。还有其他更好的方法吗。

首先,您应该确保在
ChildTable.Pid
上有一个索引,然后您可以将查询重写为类似这样的内容

select P.Pid,
       P.Pdescription,
       case when exists (
                        select *
                        from dbo.ChildTable as C
                        where P.Pid = C.Pid
                        )
         then cast(0 as bit)
         else cast(1 as bit)
       end as IsDeleteable
from dbo.ParentTable as P;
此查询检查
ChildTable
中是否存在行,您的查询正在计算每个父级的行数。检查是否存在只需找到一行,并使用索引对父表中的每一行执行一次搜索