I need help in resolving a complex SQL query. I am trying to build up the query one vlock at a time. One issue is: If a parameter for @PubNum is NULL, the query shows "..... where PubNum = '' which is an issue. What I need is if the parameter is NULL, then PubNum should not be in the where clause.
A second issue is:
- If @StartDate IS NOT NULL and @EndDate IS NOT NULL THEN RecAddDate BETWEEN @StartDate AND @EndDate
- If @StartDate IS NOT NULL and @EndDate IS NULL THEN RecAddDate BETWEEN @StartDate AND Today
- If @StartDate IS NULL and @EndDate IS NOT NULL THEN RecAddDate BETWEEN '01/01/2000' AND @EndDate
- If @StartDate IS NULL and @EndDate IS NULL THEN RecAddDate BETWEEN '01/01/2000' AND Today
Any ideas?
The complete query is:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[usp_BookItemSearch]
@BookSKU varchar(30) = NULL
,@SearchType int = NULL
,@PubNum varchar(10) = NULL
,@UserID int = NULL
,@StartDate smalldatetime = NULL
,@EndDate smalldatetime = NULL
AS
DECLARE @SQL as varchar(4000)
SET @SQL = 'SELECT RecID, PubNum, VendorName, InvoiceNum, BookSKU, RecAddDate FROM tb_BookInventoryLog]'
IF @BookSKU IS NOT NULL
BEGIN
IF @SearchType = 2
BEGIN
SET @SQLClause = ' WHERE BookSKU LIKE ''%' + @BookSKU + '''' --Ends with
END
IF @SearchType = 1
BEGIN
SET @SQLClause = ' WHERE BookSKU LIKE ''%' + @BookSKU + '%''' --Contains
END
IF @SearchType = 0
BEGIN
SET @SQLClause = ' WHERE BookSKU LIKE ''' + @BookSKU + '%''' --Starts with
END
END
IF @PubNum IS NOT NULL
BEGIN
IF @SQLClause IS NOT NULL
BEGIN
SET @SQLClause = @SQLClause + ' AND PubNum = ''' + @PubNum + ''''
END
ELSE
BEGIN
SET @SQLClause = @SQLClause + ' WHERE PubNum = ''' + @PubNum + ''''
END
END
IF @UserID IS NOT NULL
BEGIN
IF @SQLClause IS NOT NULL
BEGIN
SET @SQLClause = @SQLClause + ' AND (UserID = ' + CAST(@UserID AS VarChar) + ')'
END
ELSE
BEGIN
SET @SQLClause = @SQLClause + ' WHERE (UserID = ' + CAST(@UserID AS VarChar) + ')'
END
END
If (@StartDate Is Not Null) AND (@EndDate Is Not Null)
BEGIN
Set @SQLClause = @SQLClause + ' And (JoiningDate BETWEEN @StartDate AND @EndDate)'
END
IF (@EndDate IS NOT NULL)
BEGIN
IF (@StartDate IS NOT NULL)
BEGIN
SET @SQL = @SQL + ' WHERE RecAddDate between' + CAST(@StartDate As smalldatetime) + ' AND ' + CAST(@EndDate as smalldatetime) + ''
END
ELSE
BEGIN
SET @SQL = @SQL + ' RecAddDate BETWEEN 01/01/2000 AND @EndDate + '
END
END
SET @SQL = @SQL + @SQLClause + ' ORDER BY BookSKU, PubNum'
PRINT @SQL
--EXECUTE (@SQL)