SQL Server:连接选择查询和更新参数

时间:2014-04-11 10:21:46

标签: sql-server select join parameters

我有以下查询

SELECT 
    CAST(practice_area_id AS int) AS Id
    ,name As Name
    ,CAST(0 AS bit) AS 'Selected'
FROM 
    practice_area
ORDER BY 
    name

SELECT 
    CAST (wt.work_type_id AS int) AS Id
    ,wt.name AS Name
    ,CASE wt.work_type_id 
        WHEN (SELECT wt.work_type_id 
              WHERE wt.work_type_id IN (SELECT CAST (mwt.work_type_id AS int) AS Id
                                        FROM matter_work_type mwt 
                                        LEFT JOIN work_type wt ON mwt.work_type_id = wt.work_type_id 
                                        WHERE mwt.matter_number = '00597959')) 
          THEN CAST(1 AS bit) 
        ELSE CAST(0 AS bit) 
    END AS 'Selected'
FROM 
    practice_area pa
JOIN 
    work_type_practice_area wtpa ON wtpa.practice_area_id = pa.practice_area_id
JOIN 
    work_type wt ON wt.work_type_id = wtpa.work_type_id
WHERE 
    pa.practice_area_id = 2

以下是结果

enter image description here

第一个查询返回树列表复选框控件的所有根节点。第二个返回id = 2

的父级的所有子节点

我想要实现的是仅当第一个查询中的CAST(0 AS bit) AS 'Selected'替换为值1时,如果此根节点有选定的子节点(至少在子节点中有一个记录已选择= 1)

1 个答案:

答案 0 :(得分:0)

;with nodes as (-- your second query)    
SELECT 
    CAST(practice_area_id AS int) AS Id,
    name As Name,
    case when exists(Select * from nodes where nodes.id = practice_area.id and selected=1) 
         then 1 
         else 0 end
from
    practice_area
ORDER BY 
    name