可选的多参数SQL Server 2008搜索不返回任何内容

时间:2014-01-02 19:57:37

标签: sql sql-server sql-server-2008 stored-procedures

我正在尝试为每个参数的多参数搜索创建存储过程。下面的代码一旦执行就会返回任何内容,包括输入和不输入参数。我觉得我的'WHERE'部分存在一个逻辑错误,我只是没有看到。非常感谢任何和所有的帮助! =]

-Rock

-- =============================================
-- Author:      Rock G Bolton
-- Create date: 1/2/2014
-- Description: Gets Complaint(s) based on search parameters
-- =============================================
Create PROCEDURE [dbo].[GetComplaintBySearch] 
    @Type int = NULL,
    @Location int = NULL,
    @Status int = NULL,
    @Customer nvarchar(50) = NULL,
    @Responisble nvarchar(50) = NULL,
    @StartDateFrom datetime = NULL,
    @StartDateTo datetime = NULL,
    @DueDateFrom datetime = NULL,
    @DueDateTo datetime = NULL

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  
    [Complaints].[Id],
    [Complaints].[Type_fk],
    [Complaints].[RefNo],
    [Complaints].[Status_fk],
    [Complaints].[Reason_fk],
    [Complaints].[ProductLine_fk],
    [Complaints].[Model],
    [Complaints].[SerialNumber],
    [Complaints].[Description],
    [Complaints].[CallRecdBy],
    [Complaints].[CallRecdDate],
    [Complaints].[Responsible],
    [Complaints].[DueDate],
    [Complaints].[Customer],
    [Complaints].[ContactName],
    [Complaints].[Phone],
    [Complaints].[Email],
    [Complaints].[Source],
    [Complaints].[InitiatedBy],
    [Complaints].[StartDate]
    FROM [dbo].[Complaints] 
    WHERE ([Complaints].[Type_fk] = @Type OR @Type IS NULL)
        AND ([Complaints].[Status_fk] = @Status OR @Status IS NOT NULL)
        AND ([Complaints].[Customer] LIKE @Customer + '%' OR @Customer IS NULL)
        AND ([Complaints].[Responsible] Like @Responisble + '%' OR @Responisble IS NULL)
        AND (([Complaints].[StartDate] >= @StartDateFrom OR @StartDateFrom IS NULL) OR ([Complaints].[CallRecdDate] >= @StartDateFrom OR @StartDateFrom IS NULL))
        AND (([Complaints].[StartDate] <= @StartDateTo OR @StartDateTo IS NULL) OR ([Complaints].[CallRecdDate] <= @StartDateTo OR @StartDateTo IS NULL))
        AND ([Complaints].[DueDate] >= @DueDateFrom OR @DueDateFrom IS NULL)
        AND ([Complaints].[DueDate] <= @DueDateTo OR @DueDateTo IS NULL)

END

1 个答案:

答案 0 :(得分:3)

AND ([Complaints].[Status_fk] = @Status OR @Status IS NOT NULL)

应该是:

AND ([Complaints].[Status_fk] = @Status OR @Status IS NULL)

就像其他条件一样。你似乎有一个无关的NOT