存储过程的奇怪行为 - WHERE语句被忽略

时间:2015-12-30 16:05:20

标签: sql-server stored-procedures

我有一个存储过程,用于从我的数据库中选择某个列(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

3 个答案:

答案 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 + '%')

合并ANDOR时,应使用括号。