我目前正在尝试编写可以返回TRUE,FALSE或NEITHER的SQL搜索。虽然我目前的代码有效,但我不喜欢我必须复制并粘贴大量代码的事实,并且想知道是否有办法减少代码量。
DECLARE @FYear int = 2017
DECLARE @FQuarter char(2) = 'Q2'
DECLARE @FINANCIAL_GOAL_MET bit = NULL
IF(@FINANCIAL_GOAL_MET IS NULL)
SELECT FYear,
FQuarter,
IIF(FINANCIAL_GOAL_MET = 'TRUE', 1,0) AS Financial_Goal_Met
FROM Finances
WHERE (FYear = @FYear)
AND (FQuarter = @FQuarter)
ELSE
SELECT FYear,
FQuarter,
IIF(FINANCIAL_GOAL_MET = 'TRUE', 1,0) AS Financial_Goal_Met
FROM Finances
WHERE (FYear = @FYear)
AND (FQuarter = @FQuarter)
AND FINANCIAL_GOAL_MET = @FINANCIAL_GOAL_MET
答案 0 :(得分:2)
您可以在一个查询中执行此操作:
DECLARE @FYear int = 2017;
DECLARE @FQuarter char(2) = 'Q2';
DECLARE @FINANCIAL_GOAL_MET bit = NULL;
SELECT FYear, FQuarter,
(CASE WHEN FINANCIAL_GOAL_MET = 'TRUE' THEN 1 ELSE 0
END) AS Financial_Goal_Met
FROM Finances f
WHERE (FYear = @FYear) AND (FQuarter = @FQuarter) AND
(@FINANCIAL_GOAL_MET IS NULL OR FINANCIAL_GOAL_MET = @FINANCIAL_GOAL_MET);
对于那些不熟悉SQL Server中bit
类型的人,可以接受'TRUE'
进行比较,即使它是一个字符串。