我正在使用以下存储过程从表中选择数据到目前为止工作正常。
现在我想创建两个不同的案例而不重复整个查询: 如果输入@selection =“active”,则选择不等于statusX =“已发布”的所有内容,否则选择等于statusX =“已发布”的所有内容。
有谁能告诉我如何在这里实现这个目标?
我的存储过程(缩减列):
ALTER PROCEDURE [dbo].[FetchRequests]
@selection nvarchar(20)
AS
BEGIN
SET NOCOUNT ON;
SELECT col1,
col2,
col3,
col4,
col5,
statusX,
logStatus,
logID
FROM LogRequests
WHERE logStatus = 'active'
ORDER BY logID desc
FOR XML PATH('cols'), ELEMENTS, TYPE, ROOT('ranks')
END
非常感谢你提供任何帮助,蒂姆。
答案 0 :(得分:3)
您可以使用条件 WHERE 子句:
ALTER PROCEDURE [dbo].[FetchRequests]
@selection nvarchar(20)
AS
BEGIN
SET NOCOUNT ON;
SELECT col1,
col2,
col3,
col4,
col5,
statusX,
logStatus,
logID
FROM LogRequests
WHERE logStatus = 'active'
AND ((statusX <> 'Published' AND @selection = 'active')
OR (statusX = 'Published' AND @selection <> 'active'))
ORDER BY logID desc
FOR XML PATH('cols'), ELEMENTS, TYPE, ROOT('ranks')
END
答案 1 :(得分:2)
在AND
:
WHERE
条款
AND (@selection = 'active') = (StatusX <> 'Published')
(我看到它是其他海报提出的两条线的组合。好吧,我猜的味道问题:))
答案 2 :(得分:1)
怎么样
where
(@selection = 'active' and statusX != 'Published')
or
(@selection != 'active' and statusX = 'Published')
答案 3 :(得分:1)
您可以尝试类似
的内容SELECT col1,
col2,
col3,
col4,
col5,
statusX,
logStatus,
logID
FROM LogRequests
WHERE logStatus = 'active'
AND (
(@selection = "active" AND statusX <> "Published")
OR (@selection <> "active" AND statusX = "Published")
)
ORDER BY logID desc
FOR XML PATH('cols'), ELEMENTS, TYPE, ROOT('ranks')
答案 4 :(得分:1)
ALTER PROCEDURE [dbo].[FetchRequests]
@selection nvarchar(20)
AS
BEGIN
Declare @query as nvarchar(4000)
@query=
'SET NOCOUNT ON;
SELECT col1,
col2,
col3,
col4,
col5,
statusX,
logStatus,
logID
FROM LogRequests
WHERE logStatus = ''active'' and statusX ' +
Select case when @selection = 'active' then '<>'
else '='
END + '''Published''
ORDER BY logID desc
FOR XML PATH(''cols''), ELEMENTS, TYPE, ROOT(''ranks'')'
execute @query
END