【问题标题】:SQL Server 2005 - Building a WHERE clauseSQL Server 2005 - 构建 WHERE 子句
【发布时间】:2010-06-06 18:24:11
【问题描述】:

我有一个动态构建查询的存储过程。与此查询关联的 where 子句基于用户选择的过滤器值。不管我做什么,where 子句似乎都没有设置。

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

@whereClause 从不打印任何内容。反过来,LEN(@whereClause) 始终为 NULL。 @isVegan 和@hasSpouse 值被传递到存储过程中。这些值是我所期望的。

我做错了什么?为什么永远不会设置 @whereClause?

感谢您的帮助!

谢谢!

【问题讨论】:

    标签: sql sql-server tsql


    【解决方案1】:

    先初始化,something + NULL 永远是NULL

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

    【讨论】:

      【解决方案2】:

      我会用1=1 初始化 WHERE 子句,所以之后的所有内容都是用“AND”连接的,它永远不会为 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
      

      顺便说一句,SQL 中不需要围绕条件的括号。这不是 c#

      【讨论】:

        【解决方案3】:

        好吧,如果@Hasspouse 不大于-1,那么这些东西都不会命中。此外,如果您没有将 @whereClause 设置为任何内容,则 null + text = null

        我建议您检查 @HasSpouse 并在所有这些添加的顶部 SET @whereClause = ''

        【讨论】:

          【解决方案4】:

          小心 SQL 注入

          如果您没有使用 sp_executesql 的参数的选项,请将其设为派生表 http://beyondrelational.com/blogs/madhivanan/archive/2010/05/14/derived-table-new-approach-to-avoid-sql-injection.aspx

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-02-01
            • 2010-09-13
            • 2015-09-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-10-12
            相关资源
            最近更新 更多