编写一个可怕的SQL搜索查询

时间:2010-06-29 15:25:46

标签: sql-server-2005 tsql search

我正在开发一个似乎不起作用的搜索查询。 完整的查询是:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[usp_Item_Search]
    @Item_Num varchar(30) = NULL
    ,@Search_Type int = NULL
    ,@Vendor_Num varchar(10) = NULL
    ,@Search_User_ID int = NULL
    ,@StartDate smalldatetime = NULL
    ,@EndDate smalldatetime = NULL
AS
DECLARE @SQLstr as nvarchar(4000)

Set @SQLstr = 'SELECT RecID, Vendor_Num, Vendor_Name, InvoiceNum, Item_Num, 
(SELECT CONVERT(VARCHAR(11), RecDate, 106) AS [DD MON YYYY]) As RecDate, NeedsUpdate, RecAddUserID FROM [tbl_ItemLog] '

IF (@Item_Num IS NOT NULL)  
    Begin
        If @Search_Type = 0
            BEGIN
                Set @SQLstr = @SQLstr +  'WHERE Item_Num LIKE ''' + @Item_Num + '%'''
            END
        If @Search_Type = 1
            BEGIN
                Set @SQLstr = @SQLstr + 'WHERE Item_Num LIKE ''%' + @Item_Num + '%'''
            END
        If @Search_Type = 2
            BEGIN
                Set @SQLstr = @SQLstr + 'WHERE Item_Num LIKE ''%' + @Item_Num + ''''
            END
    End

IF (@Vendor_Num IS NOT NULL)
    Begin
        Set @SQLstr = @SQLstr + ' AND Vendor_Num = ''' + @Vendor_Num + ''''
    End

IF (Search_User_ID IS NOT NULL)
    Begin
        Set @SQLstr = @SQLstr + ' AND RecAddUserID = ' + convert(nvarchar(20),@Search_User_ID)
    End

Set @SQLstr = @SQLstr + ' AND (RecDate BETWEEN ''' + convert(nvarchar(10),@StartDate,101) + ''' AND ''' + convert(nvarchar(10),@EndDate,101) + ''')'

PRINT (@SQLstr)
--Execute (@SQLstr)

当我将参数传递给查询时,如果Vendor_Num值为空,则PRINT(@SQLstr)的输出为

SELECT RecID, Vendor_Num, Vendor_Name, InvoiceNum, Item_Num, 
(SELECT CONVERT(VARCHAR(11), RecDate, 106) AS [DD MON YYYY]) As RecDate, 
NeedsUpdate, RecAddUserID FROM [tbl_ItemLog] WHERE Item_Num LIKE '2200%' 
**AND Vendor_Num = ''** AND RecAddUserID = 2 AND (RecDate BETWEEN '01/01/2001' 
AND '12/12/2002')

我想要的输出是:

SELECT RecID, Vendor_Num, Vendor_Name, InvoiceNum, Item_Num,  
(SELECT CONVERT(VARCHAR(11), RecDate, 106) AS [DD MON YYYY]) As RecDate, 
NeedsUpdate, RecAddUserID FROM [tbl_ItemLog] WHERE Item_Num LIKE '2200%' 
AND RecAddUserID = 2 AND (RecDate BETWEEN '01/01/2001' AND '12/12/2002')

如何构造查询,如果param值为空,则不显示该字段。

1 个答案:

答案 0 :(得分:5)

尝试更改

IF (@Vendor_Num IS NOT NULL) 

IF (@Vendor_Num IS NOT NULL and LTRIM(@Vendor_Num) <> '')