我有以下简化的存储过程,其中基于输入参数,我需要在where子句中做一个案例。它不会执行,因为它说:'='
附近的语法不正确 PROCEDURE [dbo].[DataInfo]
@Allowactive BIT = 1
AS
BEGIN
Select * from tbl1 1
where (CASE @Allowactive
WHEN 0 then (t.Isactive = 1) END
AND isSubmitted = 1
END
答案 0 :(得分:0)
您的where子句如下所示
id
答案 1 :(得分:0)
您不应在这样的查询中使用参数,因为它会弄乱查询计划。当正确的使用计划根据参数进行更改时,您需要单独的查询,或者强制SQL始终重新编译。
请改为这样做:
create or alter procedure [dbo].[DataInfo] @Allowactive bit = 1
as
begin
if @Allowactive = 0
begin
Select * from tbl1 1
where Isactive = 1
AND isSubmitted = 1
end
else
begin
select * from tbl1 1
where isSubmitted = 1
end
end
代替运行单独的查询。
答案 2 :(得分:0)
似乎Zaynul Abadin Tuhin直接回答了您的问题。
但是,我相信一个案例陈述会使您想要实现的目标变得复杂。
我认为这样的查询可以满足您的期望结果:
PROCEDURE [dbo].[DataInfo]
@Allowactive BIT = 1
AS
BEGIN
SELECT * FROM tbl1 t
WHERE (@Allowactive = 1 OR (@Allowactive = 0 AND t.Isactive = 1))
AND t.isSubmitted = 1
END
答案 3 :(得分:0)
尝试运行以下命令并查看结果:
SELECT *
FROM Tbl1 AS T
WHERE CASE @Allowactive
WHEN 0 THEN 1 ELSE @Allowactive END = T.Isactive
AND
isSubmitted = 1;
如果您使用的是2012+版本,那么您也可以这样做:
SELECT *
FROM Tbl1 AS T
WHERE IIF(@Allowactive = 0, 1, @Allowactive) = T.Isactive;