if中的select语句用于比较

时间:2015-12-03 20:20:17

标签: sql select plsql

我需要比较两个select语句输出并比较它们以获得结果。但是想知道这个查询是否有任何语法错误,如果建议任何其他替代方法也会有所帮助。

if (      select h_s_effective_dt from h_s_protocol where appr_stat_id = 'AP' > select h_s_effective_dt from h_s_protocol where appr_stat_id = 'TR'     )

then appr_stat_id = 'AP' else appr_stat_id = 'TR'
end if 

2 个答案:

答案 0 :(得分:0)

我认为没有任何错误。

但是就这样使用它。

qry1 = select h_s_effective_dt from h_s_protocol where appr_stat_id = 'AP';

qry2 = select h_s_effective_dt from h_s_protocol where appr_stat_id = 'TR';

If(qry1>qry2)
then appr_stat_id = 'AP'
else appr_stat_id = 'TR' 
end if

看起来更干净

答案 1 :(得分:0)

这个怎么样?
通过将值存储到变量中,您可以在多个位置更轻松地使用它。
还要确保声明appr_stat_id,否则您无法在其中存储任何内容。数据库需要知道appr_stat_idVARCHAR2还是CHAR还是NUMBER

DECLARE
    valueX VARCHAR2(100) := '';
    valueY VARCHAR2(100) := '';
    appr_stat_id VARCHAR2(100) := '';

BEGIN
    -- Store the value in valueX or valueY, giving this sequence will only give one line back. 
    SELECT h_s_effective_dt INTO valueX FROM h_s_protocol WHERE appr_stat_id = 'AP';
    SELECT h_s_effective_dt INTO valueY FROM h_s_protocol WHERE appr_stat_id = 'TR';

    IF (valueX>valueY) THEN 
        appr_stat_id = 'AP'; 
    ELSE
        appr_stat_id = 'TR';
    END IF; 
END;
/