如何在SQL Server中编写IF THEN DO语句

时间:2014-05-24 22:07:41

标签: sql sql-server sas

我有一个SAS code,我想将其转换为SQL code。我被困在SAS的一个功能IF THEN DO。代码如下所示:

IF FLAG = 'Y' AND ACCT = ' ' THEN DO;
ORIG_AMT = -(ORIG_AMT);
BAL = -(BAL);
AVAIL_BAL = -(AVAIL_BAL);
PROC_AMT = -(PROC_AMT);
END;

请建议如何将此代码转换为SQL server代码。提前谢谢!

2 个答案:

答案 0 :(得分:3)

如果此逻辑位于数据集中,那么您正在使用列。如果是这样,您可以在case中使用select语句:

select (case when FLAG = 'Y' AND ACCT = ' ' then - orig_amt else orig_amt end) as orig_amt,
       (case when FLAG = 'Y' AND ACCT = ' ' then - bal else bal end) as bal,
       (case when FLAG = 'Y' AND ACCT = ' ' then - avail_bal else avail_bal end) as avail_bal,
       (case when FLAG = 'Y' AND ACCT = ' ' then - proc_amt else proc_amt end) as proc_amt

答案 1 :(得分:1)

注意:我根据Josh的评论更新了我的答案

假设FLAGACCTORIG_AMTORIG_AMTBAL是变量(SAS),那么您可以重写原始来源因此使用T-SQL语法的代码:

IF @FLAG = 'Y' AND (@ACCT = '' OR @ACCT IS NULL)
BEGIN
    SET @ORIG_AMT = -(@ORIG_AMT);
    SET @BAL = -(@BAL);
    SET @AVAIL_BAL = -(@AVAIL_BAL);
    SET @PROC_AMT = -(@PROC_AMT);
END;

IF @FLAG = 'Y' AND (@ACCT = '' OR @ACCT IS NULL)
    SELECT 
        @ORIG_AMT = -(@ORIG_AMT);
        @BAL = -(@BAL);
        @AVAIL_BAL = -(@AVAIL_BAL);
        @PROC_AMT = -(@PROC_AMT);

    SELECT 
        @ORIG_AMT = -(@ORIG_AMT);
        @BAL = -(@BAL);
        @AVAIL_BAL = -(@AVAIL_BAL);
        @PROC_AMT = -(@PROC_AMT);
    WHERE @FLAG = 'Y' AND (@ACCT = '' OR @ACCT IS NULL)