如何在if语句中选择

时间:2015-12-31 13:56:15

标签: sql sql-server tsql

我想测试两个TaskChangeLogID,其中ID'28'的NewRollback为0,而ID'31'的NewRollback为1。

我想确保根据哪个ID调用,它会选择正确的NewRollback数字。我在新窗口中应用下面的代码时出错,所以只需要帮助调整它并学习如何在将来测试这样的事情。我只在IF语句行中收到错误。

SELECT isnull(NewRollback, 0) FROM Core.TaskChangeLog
WHERE TaskChangeLogID =  28

SELECT isnull(NewRollback, 0) FROM Core.TaskChangeLog
WHERE TaskChangeLogID =  31

IF (NewRollback = 1)

Select * from Core.TaskChangeLog where NewRollback = 1

ELSE
    BEGIN

    Select * from Core.TaskChangeLog where NewRollback = 0

    END

2 个答案:

答案 0 :(得分:2)

您不需要IF条件才能执行此操作AND/OR逻辑将完成此任务

试试这种方式

Select * from Core.TaskChangeLog 
where (NewRollback = 1 and askChangeLogID =  28)
   OR (NewRollback = 0 and askChangeLogID =  31)

要根据select结果执行某些操作,请尝试使用此

IF EXISTS (Select * from Core.TaskChangeLog 
    where NewRollback = 1 and askChangeLogID =  28) -- Replace with your ID
BEGIN 
 --some action
END
IF EXISTS (Select * from Core.TaskChangeLog 
    where NewRollback = 0 and askChangeLogID =  28)
BEGIN
 --some action
END

答案 1 :(得分:2)

如何将所有这些放在一个查询中?这是我对你想要的逻辑的最好猜测:

Select *
from Core.TaskChangeLog
where NewRollback = (SELECT COALESCE(NewRollback, 0)
                     FROM Core.TaskChangeLog
                     WHERE TaskChangeLogID = XX
                    );

您的代码失败,因为NewRollback中的IF未定义。您可以使用变量,但这会使代码复杂化。而且,代码应该简化而不是更复杂。