我正在尝试将以下Access查询转换为T-SQL,但我遇到了IIF语句问题。
访问查询
SELECT
qry_LAB_LOAD_Prequery2.Asset AS SITE_REF,
Format([Det],"00000") AS DET_,
IIf(IsNull([MT]),"0",IIf(Right([SP_Ref],2)="WZ"
And IsNull([LabLoadFileSuffix_MT])
And [MT]>0,CStr([MT]) & "CT",CStr([MT]) & [LabLoadFileSuffix_MT])) AS MT_COUNT,
IIf(IIf(IsNull([MT]),0,[MT])>=IIf(IsNull([IM]),0,[IM]),0,
IIf(IsNull([IM]),"0",IIf(Right([SP_Ref],2)="WZ"
And IsNull([LabLoadFileSuffix_IM]),CStr([IM])
& "CT",CStr([IM]) & [LabLoadFileSuffix_IM]))) AS IM_COUNT,
qry_LAB_LOAD_Prequery2.[2012 Sample Point] AS SP_REF, qry_LAB_LOAD_Prequery2.Area
FROM qry_LAB_LOAD_Prequery2
WHERE (((IIf(IsNull([IM]),0,[IM])+IIf(IsNull([MT]),0,[MT]))>0));
我试图转换它的一部分。任何人都可以帮我纠正嵌套的IID语句,因为我不确定。
SQL查询
SELECT qry_LAB_LOAD_Prequery2.Asset AS SITE_REF,
RIGHT('00000' + CAST([Det] AS VARCHAR(5)),5) AS DET_,
----- (the nested iff statements)
qry_LAB_LOAD_Prequery2.[2012 Sample Point] AS SP_REF,
qry_LAB_LOAD_Prequery2.Area
FROM qry_LAB_LOAD_Prequery2
where (ISNull([IM],0) + ISNULL([MT],0)) > 0
答案 0 :(得分:3)
要转换嵌套的IIF,您需要用户CASE。
让我们拿第一个:
重新格式化我得到:
IIf(
IsNull([MT]),
"0",
IIf(Right([SP_Ref],2)="WZ"
And IsNull([LabLoadFileSuffix_MT])
And [MT]>0,
CStr([MT]) & "CT",
CStr([MT]) & [LabLoadFileSuffix_MT]
)
) AS MT_COUNT,
转换为:
CASE
WHEN [MT] IS NULL
THEN "0",
ELSE
CASE
WHEN Right([SP_Ref],2) = "WZ"
AND ([LabLoadFileSuffix_MT] IS NULL
AND [MT]>0
THEN
CAST([MT] AS VARCHAR) + "CT"
ELSE
CAST([MT] AS VARCHAR) + [LabLoadFileSuffix_MT]
END
END AS MT_COUNT,
简化为:
CASE
WHEN [MT] IS NULL
THEN "0",
ELSE
CAST([MT] AS VARCHAR)
+ CASE
WHEN Right([SP_Ref],2) = "WZ"
AND ([LabLoadFileSuffix_MT] IS NULL
AND [MT]>0
THEN
"CT"
ELSE
[LabLoadFileSuffix_MT]
END
END AS MT_COUNT,
对于第二个,我重新格式化,然后将其转换为以下
CASE WHEN
CASE
WHEN [MT] IS NULL THEN 0
ELSE [MT]
END
>=
CASE
WHEN [IM] IS NULL THEN 0
ELSE [IM]
END ,
THEN 0,
ELSE
CASE
WHEN [IM] IS NULL THEN "0"
ELSE
CASE
WHEN Right([SP_Ref],2) = "WZ" AND [LabLoadFileSuffix_IM] IS NULL THEN CAST([IM] AS VARCHAR) + "CT"
ELSE CAST([IM] AS VARCHAR) + [LabLoadFileSuffix_IM]
END
END
END
AS IM_COUNT,
Whick缩减为
CASE
WHEN ISNULL([MT], 0) > = ISNULL([IM], 0)
THEN 0,
ELSE
CASE
WHEN [IM] IS NULL THEN "0"
ELSE
CAST([IM] AS VARCHAR) +
CASE
WHEN Right([SP_Ref],2) = "WZ" AND [LabLoadFileSuffix_IM] IS NULL THEN "CT"
ELSE [LabLoadFileSuffix_IM]
END
END
END
AS IM_COUNT,
这两个列基本上归结为两个非常相似的表达式。
答案 1 :(得分:1)
尝试嵌套的case语句。
所以只需占用前2行:
IIf(IsNull([MT]),"0",IIf(Right([SP_Ref],2)="WZ"
And IsNull([LabLoadFileSuffix_MT])
会变成
CASE WHEN MT IS NULL
THEN 0
ELSE
CASE WHEN RIGHT(SP_Ref, 2) = "WZ" AND LabLoadFileSuffix_MT IS NULL
THEN
...
ELSE ...
END
END