我正在试图弄清楚如何在where子句中返回可能的多个值。
这是我的查询
SELECT *,
ISNULL(nStatus, '0') Status,
ISNULL(dtUsed, 0) dtUsed,
ISNULL(sStaffID, '') StaffID,
ISNULL((SELECT sName FROM GCS_tbBranch WHERE nSeq=GCS_tbGC.nBranchNo), '') nBranchName,
ISNULL((SELECT dtValidEnd FROM GCS_tbGCGroup WHERE nGroupNo = GCS_tbGC.nGroupSeq), 0) dtValidUntil,
ISNULL((SELECT dtCreated FROM GCS_tbGCGroup WHERE nGroupNo=GCS_tbGC.nGroupSeq), 0) dtCreated,
ISNULL((SELECT nPrice FROM GCS_tbGCGroup WHERE nGroupNo=GCS_tbGC.nGroupSeq), 0) nPrice,
ISNULL(sRemarks, ' ') sRemarks
FROM GCS_tbGC WHERE sGCNo LIKE @sGCNo+'%' AND nGroupSeq IN (SELECT nGroupNo FROM GCS_tbGCGroup WHERE
CASE
WHEN @sClass = 'QNS' OR @sClass = 'IFL' THEN (sClass = 'QNS' OR sClass = 'IFL')
ELSE
@sClass
END
)
其中,如果变量@sClass持有'QNS' or 'IFL'
,它将返回具有sClass = 'QNS' OR sClass = 'IFL'
的记录,否则,只返回@sClass变量的值。
编辑:每当我运行此查询时,它都会返回此异常
Incorrect syntax near ' = ' is invalid.
答案 0 :(得分:0)
我认为CASE表达式不适合这项工作。请尝试以下查询。
SELECT *,
ISNULL(nStatus, '0') Status,
ISNULL(dtUsed, 0) dtUsed,
ISNULL(sStaffID, '') StaffID,
ISNULL((SELECT sName FROM GCS_tbBranch WHERE nSeq=GCS_tbGC.nBranchNo), '') nBranchName,
ISNULL((SELECT dtValidEnd FROM GCS_tbGCGroup WHERE nGroupNo = GCS_tbGC.nGroupSeq), 0) dtValidUntil,
ISNULL((SELECT dtCreated FROM GCS_tbGCGroup WHERE nGroupNo=GCS_tbGC.nGroupSeq), 0) dtCreated,
ISNULL((SELECT nPrice FROM GCS_tbGCGroup WHERE nGroupNo=GCS_tbGC.nGroupSeq), 0) nPrice,
ISNULL(sRemarks, ' ') sRemarks
FROM GCS_tbGC
WHERE sGCNo LIKE @sGCNo+'%'
AND nGroupSeq IN (
SELECT nGroupNo
FROM GCS_tbGCGroup
WHERE
@sClass IN('QNS', 'IFL') AND sClass IN('QNS', 'IFL')
UNION ALL
SELECT @sClass
WHERE
@sClass NOT IN('QNS', 'IFL')
);
答案 1 :(得分:0)
CASE
会返回标量并且应该像一个一样使用 - 您无法按照自己的方式操纵条件。
尝试更简单的表达式:
and (
nGroupSeq = @sClass
or @sClass = 'QNS' and nGroupSeq = 'IFL'
or @sClass = 'IFL' and nGroupSeq = 'QNZ'
)
或
and (
nGroupSeq = @sClass
or @sClass in ('QNS', 'IFL') and nGroupSeq in ('QNS', 'IFL'))
)
答案 2 :(得分:0)
管理将其关闭。
认为我可以在IN关键字中插入case语句,我可以根据情况使用2个case语句。
这是我的解决方案。
SELECT *,
ISNULL(nStatus, '0') Status,
ISNULL(dtUsed, 0) dtUsed,
ISNULL(sStaffID, '') StaffID,
ISNULL((SELECT sName FROM GCS_tbBranch WHERE nSeq=GCS_tbGC.nBranchNo), '') nBranchName,
ISNULL((SELECT dtValidEnd FROM GCS_tbGCGroup WHERE nGroupNo = GCS_tbGC.nGroupSeq), 0) dtValidUntil,
ISNULL((SELECT dtCreated FROM GCS_tbGCGroup WHERE nGroupNo=GCS_tbGC.nGroupSeq), 0) dtCreated,
ISNULL((SELECT nPrice FROM GCS_tbGCGroup WHERE nGroupNo=GCS_tbGC.nGroupSeq), 0) nPrice,
ISNULL(sRemarks, ' ') sRemarks
FROM GCS_tbGC WHERE sGCNo LIKE @sGCNo+'%' AND nGroupSeq IN (SELECT nGroupNo FROM GCS_tbGCGroup WHERE sClass IN (
CASE @sClass
WHEN 'QNS' THEN 'IFL'
WHEN 'IFL' THEN 'IFL'
ELSE
@sClass
END
,
CASE @sClass
WHEN 'QNS' THEN 'QNS'
WHEN 'IFL' THEN 'QNS'
ELSE
''
END
)
)
欢迎任何更好的查询。我希望你能提出进一步缩短/增强查询的建议。谢谢,更有力量!