下面是我在T-SQL中的存储过程。我有两个参数@id
和@questionId
。 Select语句使用两个参数进行选择。
我正在寻找的方法是如果参数的值为0则不使用条件。详细地,如果@id的值为0,则过滤pa.Id = @id
不应执行的地方以及@questionId =0
时,并且pa.QuestionId = @questionId
不应执行。
ALTER PROCEDURE[dbo].[spOptions]
(@id INT, @questionId INT)
AS
BEGIN
SELECT *
FROM PossibleAnswers pa
INNER JOIN vFormAnswers fa ON pa.QuestionId = fa.QuestionId
WHERE pa.Id = @id
AND pa.QuestionId = @questionId
END
GO
答案 0 :(得分:0)
您可以尝试一下。在这里,如果将参数传递为0,则它将执行或条件0 = 0(为true)并考虑所有记录。
ALTER PROCEDURE[dbo].[spOptions]
( @id int=0, @questionId int=0 ) ---- here pass default value as 0 so this is optional to pass from front end
AS
BEGIN
select * from PossibleAnswers pa
inner join vFormAnswers fa
on pa.QuestionId = fa.QuestionId
where (pa.Id = @id or @id = 0) ---- here if @id = 0 then condition will be 0=0
and (pa.QuestionId = @questionId or @questionId=0)
END
GO