我试图做一个包含CASE语句的WHERE子句。如果我的字段等于某个文本值,那么我想应用一组逻辑,如果它包含一个单独的值,那么我希望它以不同的方式过滤。
我有这段代码,但我无法使其正常工作:
AND CASE DO11_DOCUM_MG36 WHEN 'TSC-ORDINE-RIC'
THEN
(CONVERT(DATE,ISNULL(dbo.DO31_DOCCORPOORD.DO31_DATACONS,DATEADD(day,ISNULL(dbo.DO17_DOCTESTAPERS.DO17_NUMPERS4,15),dbo.DO12_DOCTESTARIF.DO12_DATAVSCONF)),102) <= '2016-02-29' AND dbo.DO12_DOCTESTARIF.DO12_DATAVSCONF is not null) AND (dbo.DO36_DOCCORPOEST.DO36_DATAST1 is null or CONVERT(DATE,dbo.DO36_DOCCORPOEST.DO36_DATAST1,102) >= '2016-02-01')
ELSE
(CONVERT(DATE,ISNULL(dbo.DO31_DOCCORPOORD.DO31_DATACONS,DATEADD(day,ISNULL(dbo.DO17_DOCTESTAPERS.DO17_NUMPERS4,15),dbo.DO12_DOCTESTARIF.DO12_DATAVSCONF)),102) BETWEEN '2016-02-01' AND '2016-02-29' AND dbo.DO12_DOCTESTARIF.DO12_DATAVSCONF is not null)
END
由于
答案 0 :(得分:0)
我的格式不同,以便于阅读。 CASE语句的逻辑应该是CASE WHEN ......那么...... ELSE ... END。你可以在WHEN语句中加入AND子句,但我不知道你可以像你一样在你的THEN子句中使用AND。
你的WHEN语句不会产生一个boolian值,没有'WHEN x = y THEN'只有'WHEN x THEN'。
在陈述开头的CASE和WHEN之间也应该没有任何内容,这永远不会起作用。
请同时开始使用表别名,它将使您的代码更容易阅读。
AND CASE DO11_DOCUM_MG36
WHEN 'TSC-ORDINE-RIC'
THEN (
CONVERT(DATE, ISNULL(dbo.DO31_DOCCORPOORD.DO31_DATACONS, DATEADD(day, ISNULL(dbo.DO17_DOCTESTAPERS.DO17_NUMPERS4, 15), dbo.DO12_DOCTESTARIF.DO12_DATAVSCONF)), 102) <= '2016-02-29'
AND dbo.DO12_DOCTESTARIF.DO12_DATAVSCONF IS NOT NULL
)
AND (
dbo.DO36_DOCCORPOEST.DO36_DATAST1 IS NULL
OR CONVERT(DATE, dbo.DO36_DOCCORPOEST.DO36_DATAST1, 102) >= '2016-02-01'
)
ELSE (
CONVERT(DATE, ISNULL(dbo.DO31_DOCCORPOORD.DO31_DATACONS, DATEADD(day, ISNULL(dbo.DO17_DOCTESTAPERS.DO17_NUMPERS4, 15), dbo.DO12_DOCTESTARIF.DO12_DATAVSCONF)), 102) BETWEEN '2016-02-01'
AND '2016-02-29'
AND dbo.DO12_DOCTESTARIF.DO12_DATAVSCONF IS NOT NULL
)
END
CASE语句逻辑应该是这样的;
CASE
WHEN a.Field1 = 'SomeText'
THEN CONVERT(DATE, a.DateTimeField)
WHEN a.Field1 = 'DifferentText' AND a.Field2 = 'YetMoreText'
THEN CONVERT(DATE, a.DifferentDateTimeField)
ELSE 'DoSomethingElse'
END
进一步阅读;
http://www.techonthenet.com/sql_server/functions/case.php
阅读你的逻辑,我不相信你在这里需要一个案例陈述,像你这样的事情;
AND
(
CONVERT(DATE, ISNULL(dbo.DO31_DOCCORPOORD.DO31_DATACONS, DATEADD(day, ISNULL(dbo.DO17_DOCTESTAPERS.DO17_NUMPERS4, 15), dbo.DO12_DOCTESTARIF.DO12_DATAVSCONF)), 102) <= '2016-02-29'
AND dbo.DO12_DOCTESTARIF.DO12_DATAVSCONF IS NOT NULL
)
AND
(
(
dbo.DO36_DOCCORPOEST.DO36_DATAST1 IS NULL
OR CONVERT(DATE, dbo.DO36_DOCCORPOEST.DO36_DATAST1, 102) >= '2016-02-01'
)
OR
CONVERT(DATE, ISNULL(dbo.DO31_DOCCORPOORD.DO31_DATACONS, DATEADD(day, ISNULL(dbo.DO17_DOCTESTAPERS.DO17_NUMPERS4, 15), dbo.DO12_DOCTESTARIF.DO12_DATAVSCONF)), 102) BETWEEN '2016-02-01'AND '2016-02-29'
)
根据你的评论,你可以使用它;
AND (
( OrderType = 'TSC-ORDINI-RIC'
AND
'WHERE CONDITION 1 GOES HERE'
)
OR
( OrderType = 'TSC-ORDINI'
AND
'WHERE CONDITION 2 GOES HERE'
)
)