如果子表中的条件满足则返回参数

时间:2020-01-27 07:07:17

标签: sql sql-server stored-procedures sql-server-2012 return-value

我有这样的桌子

父表

id, column1,  etc
-    -         -     
-    -         -     

详细信息

id, parent_id, column1, actual_finish (value is true/false)
 -     -            -           -      
 -     -            -           -          

我想检查所有列actual_finish是否都为true,然后返回1(我认为这将是return参数),否则返回0。

例如

父母

id   column1  etc,
------------------
1    value1    a 

详细信息

id, parent_id, column1, actual_finish (value is true/false)
------------------------------------------------------------
1       1         a           true
2       1         b           false

这将返回0,因为第二行的实际完成值是false,但是如果第二行的列Actual_finish更新为true,则返回1

我想创建一个基于actual_finish表中的列detail返回0或1的存储过程。

有人可以帮我吗?

4 个答案:

答案 0 :(得分:0)

您可以使用的查询是

Select returnvalue= case when totalCount=trueCount then 1 else 0 end 
from
(select 
    trueCount=count (case when actual_finish ='true' then 1 else 0 end), 
    totalCount = count(1)
from
parent p left join detail d
    on p.id=d.parent_id
group by p.id
)T

这是假设如果明细表中没有父ID的行,则返回false

答案 1 :(得分:0)

尝试使用,

{
  "fault": {
    "code": 900901,
    "message": "Invalid Credentials",
    "description": "Access failure for API: /embargoQA/v1, version: v1 status: (900901) - Invalid Credentials. Make sure you have given the correct access token"
  }
}

SP,类似..

select min(case when actual_finish='true' then 1 else 0 end) from tab_Detail where parent_id=1;

Fiddle

答案 2 :(得分:0)

我认为要求是,即使存在一行,其中Actual_fnish为false,然后返回0。

declare @res as int=1
If exists(select 1 from dbo.tbldetail where actual_finish='false')
set @res=0

actual_finish应该是BIT数据类型(0或1)

答案 3 :(得分:0)

我建议使用exists。要处理parents中的多行:

select p.*,
       (case when exists (select 1
                          from details d
                          where d.parent_id = p.id and
                                d.actual_finish = 'false'
                         )
             then 0 else 1
        end) as flag
from parents p;