views:

47

answers:

1

I am having problems trying to create a fairly simple dynamic SQL query. The variables don't display the values they contain when I PRINT @SQLString. Any ideas?

    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
+2  A: 

You are adding @ItemNum and @VendorNum to @SQLString correctly, but you aren't adding the other 3 variables correctly. You have to cast them as varchar's and concatenate them on to @SQLString the same way you are doing the other ones.

For example, here's how the @RecSearchUserID block should look:

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

Also, you do need to be careful about your input variables containing apostrophes as the other commenters have pointed out in order to protect against SQL injection...

David