开发者

SQL Server 2005 - Building a WHERE clause

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开发者_如何学C 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!


Initialize it first, something + NULL is always NULL

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


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#


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 = ''


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜