如何根据上层查询sql server编写条件

时间:2016-10-19 16:25:16

标签: sql-server

我想用sql中的if语句检查记录这里是我的查询

declare @reporttitle nvarchar(100)

select   
    rs.risk_assesment_id, rs.grade, rs.assessmentdate,
    pat.name, pat.card_id_no, pat.dob, pat.age, pat.mrn,  
    pat.nationality, pat.mobileno,
    @reporttitle as title
from 
    riskassessment_detail rs 
where 
    rs.risk_assesment_id = 22 

IF ((SELECT r.grade 
     FROM riskassessment_detail r 
     WHERE r.risk_assesment_id = 22) ='A') 
   SET @reporttitle = 'AT RISK (15-18)* (A)';

reporttitle最终成为null;我想得到文本如何解决我的问题

1 个答案:

答案 0 :(得分:0)

如果没有错,您需要将IF条件移到SELECT查询之上,以便在满足'AT RISK (15-18)* (A)'条件时使用IF字符串设置变量并将其显示在SELECT

declare @reporttitle nvarchar(100)

IF EXISTS (SELECT  1
     FROM riskassessment_detail r 
     WHERE r.risk_assesment_id = 22
       AND r.grade='A') 
   SET @reporttitle = 'AT RISK (15-18)* (A)';


select   
    rs.risk_assesment_id, rs.grade, rs.assessmentdate,
    pat.name, pat.card_id_no, pat.dob, pat.age, pat.mrn,  
    pat.nationality, pat.mobileno,
    @reporttitle as title
from 
    riskassessment_detail rs 
where 
    rs.risk_assesment_id = 22