编写动态SQL查询

时间:2010-06-23 02:55:45

标签: tsql dynamic-sql

我在尝试创建一个相当简单的动态SQL查询时遇到问题。在PRINT @SQLString时,变量不显示它们包含的值。有什么想法吗?

    ALTER PROCEDURE [dbo].[usp_ItemSearch]
    @ItemNum varchar(30) = NULL
    ,@SearchFilter int
    ,@VendorNum varchar(10) = NULL
    ,@RecUserID int = NULL
    ,@StartDate smalldatetime = NULL
    ,@EndDate smalldatetime = NULL
AS
DECLARE @SQLString as varchar(1000)

SET @SQLString = 'SELECT RecID, VendorNum, VendorName, PORelNum, InvoiceNum, ItemNum, RecAddDate, LastUpdated FROM tbl_Processor_ItemDscLog'

IF @ItemNum IS NOT NULL
    BEGIN
        IF  @SearchFilter = 2
            BEGIN
                SET @SQLString = @SQLString + ' WHERE ItemNum LIKE ''%' + @ItemNum + ''''   --Ends with
            END
        IF  @SearchFilter = 1
            BEGIN
                SET @SQLString = @SQLString + ' WHERE ItemNum LIKE ''%' + @ItemNum + '%'''  --Contains
            END
        IF  @SearchFilter = 0
            BEGIN
                SET @SQLString = @SQLString + ' WHERE ItemNum LIKE ''' + @ItemNum + '%'''   --Starts with
            END
    END

IF @VendorNum IS NOT NULL
    BEGIN
        SET @SQLString = @SQLString + ' WHERE VendorNum = ''' + @VendorNum + ''''
    END

IF @RecSearchUserID IS NOT NULL
    BEGIN
        SET @SQLString = @SQLString + ' AND (RecAddUserID = @RecUserID)'
    END

IF (@EndDate IS NOT NULL)
    BEGIN
        IF (@StartDate IS NOT NULL) 
            BEGIN
                SET @SQLString = @SQLString +  ' WHERE RecAddDate between @StartDate AND @EndDate '
            END
        ELSE
            BEGIN
                SET @SQLString = @SQLString +  ' RecAddDate BETWEEN 01/01/1996 AND @EndDate + '
            END
    END

SET @SQLString = @SQLString +  ' ORDER BY ItemNum, VendorNum'
PRINT @SQLString

1 个答案:

答案 0 :(得分:3)

您正在将@ItemNum和@VendorNum正确添加到@SQLString,但您没有正确添加其他3个变量。你必须将它们转换为varchar并将它们连接到@SQLString,就像你在做其他的一样。

例如,以下是@RecSearchUserID块的外观:

IF @RecSearchUserID IS NOT NULL
    BEGIN
        SET @SQLString = @SQLString + ' AND (RecAddUserID = ' + CAST(@RecUserID AS VarChar) + ')'
    END

另外,你需要注意包含撇号的输入变量,正如其他评论者指出的那样,以防止SQL注入......