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