1

I have a stored procedure that is dynamically building a query. The where clause associated with this query is based on filter values selected by a user. No matter what I do though, the where clause does not seem to get set.

-- Dynamically build the WHERE clause based on the filters
DECLARE @whereClause as nvarchar(1024)
IF (@hasSpouse > -1)
BEGIN
  IF (@hasSpouse = 0)
    SET @whereClause='p.[HasSpouse]=0'
  ELSE
    SET @whereClause='(p.[HasSpouse]=1 OR p.[HasSpouse] IS NULL)'
  END

  -- Dynamically add the next filter if necessary
  IF (@isVegan > -1)
  BEGIN
    IF (LEN(@whereClause) > 0)
    BEGIN
      SET @whereClause = @whereClause + ' AND '
    END

    IF (@isVegan = 0)
      SET @whereClause = @whereClause + 'c.[IsVegan]=0'
    ELSE
      SET @whereClause = @whereClause + '(c.[IsVegan]=1 OR c.[IsVegan] IS NULL)'
  END

  PRINT @whereClause

The @whereClause never prints anything. In turn, the LEN(@whereClause) is always NULL. The @isVegan and @hasSpouse values are passed into the stored procedure. The values are what I expected.

What am I doing wrong? Why is the @whereClause never being set?

Thank you for your help!

Thank you!

4 Answers 4

6

Initialize it first, something + NULL is always NULL

DECLARE @whereClause as nvarchar(1024)
SET @whereClause  = ''
2

I'd initialise the WHERE clause with 1=1 so everything after that is concatenation with 'AND' and it's never NULL

DECLARE @whereClause as nvarchar(1024)
SET @whereClause = '1=1'

IF @hasSpouse > -1
BEGIN
  IF @hasSpouse = 0
    SET @whereClause = @whereClause + ' AND p.[HasSpouse]=0'
  ELSE
    SET @whereClause = @whereClause + ' AND (p.[HasSpouse]=1 OR p.[HasSpouse] IS NULL)'
END

-- Dynamically add the next filter if necessary
IF @isVegan > -1
BEGIN
    IF @isVegan = 0
      SET @whereClause = @whereClause + ' AND c.[IsVegan]=0'
    ELSE
      SET @whereClause = @whereClause + ' AND (c.[IsVegan]=1 OR c.[IsVegan] IS NULL)'
END

PRINT @whereClause

BTW, parenthesis around conditions are not needed in SQL. It aint c#

0
2

Well, if @Hasspouse isn't greater than -1 then none of that stuff will hit. Also, if you don't have @whereClause set to anything then null + text = null

I recommend that you check @HasSpouse and at the top of all this add SET @whereClause = ''

0

Beware of SQL injection

If you don't have an option to use parameters with sp_executesql, make it as a derived table http://beyondrelational.com/blogs/madhivanan/archive/2010/05/14/derived-table-new-approach-to-avoid-sql-injection.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.