我有一个存储过程,用于从我的数据库中选择某个列(EventId) = x
的所有行。当我在Visual Studio中使用GridView时,这很好用。然后我在GridView中添加了一个搜索功能,它也可以搜索得很好。
但是,添加了搜索功能后,我的存储过程不会根据EventId = x
进行选择。相反,它显示所有行,尽管id。为什么?需要改变什么?例如,如果EventId = 80
,它仍会显示EventId = 7
9和78
等。
代码没有搜索有效!
ALTER PROCEDURE [dbo].[spGetAllRegistrantRapidResponse]
-- Add the parameters for the stored procedure here
@EventId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT *
FROM Registrant
WHERE EventId = @EventId
END
代码搜索不起作用!
ALTER PROCEDURE [dbo].[spGetAllRegistrantRapidResponse]
-- Add the parameters for the stored procedure here
@EventId int,
@CompletedByFirstName nvarchar(20),
@CompletedByLastName nvarchar(25),
@FirstName nvarchar(20),
@LastName nvarchar(25),
@PaymentMethod nvarchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT *
FROM Registrant
WHERE EventId = @EventId AND
CompletedByFirstName LIKE '%' + @CompletedByFirstName + '%'
OR CompletedByLastName LIKE '%' + @CompletedByLastName + '%'
OR FirstName LIKE '%' + @FirstName + '%'
OR LastName LIKE '%' + @LastName + '%'
OR PaymentMethod LIKE '%' + @PaymentMethod + '%'
END
答案 0 :(得分:3)
请限定您的条件; AND条件优先于此
SELECT *
FROM Registrant
WHERE EventId = @EventId AND
(CompletedByFirstName LIKE '%' + @CompletedByFirstName + '%'
OR CompletedByLastName LIKE '%' + @CompletedByLastName + '%'
OR FirstName LIKE '%' + @FirstName + '%'
OR LastName LIKE '%' + @LastName + '%'
OR PaymentMethod LIKE '%' + @PaymentMethod + '%')
END
答案 1 :(得分:2)
and
运算符的precedence运算符高于or
运算符,因此您需要使用括号,否则事件ID检查仅适用于第一次like
比较:
WHERE EventId = @EventId AND (
CompletedByFirstName LIKE '%' + @CompletedByFirstName + '%'
OR CompletedByLastName LIKE '%' + @CompletedByLastName + '%'
OR FirstName LIKE '%' + @FirstName + '%'
OR LastName LIKE '%' + @LastName + '%'
OR PaymentMethod LIKE '%' + @PaymentMethod + '%'
)
答案 2 :(得分:1)
我认为你应该尝试类似的事情:
WHERE EventId = @EventId AND
(CompletedByFirstName LIKE '%' + @CompletedByFirstName + '%'
OR CompletedByLastName LIKE '%' + @CompletedByLastName + '%'
OR FirstName LIKE '%' + @FirstName + '%'
OR LastName LIKE '%' + @LastName + '%'
OR PaymentMethod LIKE '%' + @PaymentMethod + '%')
合并AND
和OR
时,应使用括号。