SP WHERE中的参数条件的CASE

时间:2015-08-26 17:04:13

标签: sql stored-procedures parameters case where

我有一个包含5个参数的存储过程,所有参数都默认为-1。当它们都为-1时,存储过程返回所有行。否则,我试图根据传递的值编写select语句来限制。我在SELECT语句之间使用了UNION和条件,但它返回了所有内容所以我需要一种方法来限制传递的值,如果传递-1则不需要对该参数进行限制。我想在WHERE中做一个CASE,但不知道我会怎么做。它可能类似于以下内容。

DECLARE @SQL NVARCHAR(MAX)
SET @SQL =N'SELECT computerType, ComputerName, DriveType, DriveLetter,
      Encryption, ProtectType, Cipher
   FROM computers
   WHERE 1=1 '
IF (@ComputerType > -1 and @ComputerType<> 100)
    SET @SQL = @SQL + N'
    AND @ComputerType = ComputerType '
IF (@DriveType > -1 and @DriveType<> 100)
    SET @SQL = @SQL + N'
    AND @DriveType = DriveType '
--     IF FOR EACH PARAMETER
EXEC (@SQL)

如果我使用动态SQL编写它,我会做这样的事情:

import scala.language.implicitConversions

// 1.
// If conversions are defined this way, the program compiles.
// But many sources insist that compiler also looks in the source/target companions for conversions.
object Conversions {
  implicit def varToExpr(v: Var): VarExpr = new VarExpr(v)
  implicit def constToExpr(c: Const): ConstExpr = new ConstExpr(c)
}
import Conversions._

class Var(val name: String)

class Const(val value: String)

// 2.
// These conversions do not work for e1-e4 (see below), but e5-e10 compile.
object Var {
  implicit def varToExpr(v: Var): VarExpr = new VarExpr(v)
}

object Const {
  implicit def constToExpr(c: Const): ConstExpr = new ConstExpr(c)
}

trait Expr {
  def +(right: Expr): PlusExpr = PlusExpr(this, right)
  def :+(right: Expr): PlusExpr = PlusExpr(this, right)

  // 3.
  // These do not work at all.
  implicit def varToExpr(v: Var): VarExpr = new VarExpr(v)
  implicit def constToExpr(c: Const): ConstExpr = new ConstExpr(c)
}

case class ConstExpr(c: Const) extends Expr
case class VarExpr(v: Var) extends Expr
case class PlusExpr(left: Expr, right: Expr) extends Expr

class Test {
  def main(args: Array[String]) {
    val a = new Var("a")
    val b = new Var("b")
    val c = new Const("c")

    // Want to be able to write things like that.
    // The first 4 work only with the 1-st way of defining the implicit conversions.
    // For the 2nd way they give
    // Error:(__, __) type mismatch;
    // found   : Const (or Var, or VarExpr)
    // required: String
    val e1 = a + b
    val e2 = c + c
    val e3 = (a + b) + c
    val e4 = a + VarExpr(b)

    // This compiles with both 1st and 2nd ways.
    val e5 = ConstExpr(c) + b
    val e6 = VarExpr(a) + c

    val e7 = a :+ b
    val e8 = c :+ c
    val e9 = (a :+ b) :+ c
    val e10 = a :+ VarExpr(b)
  }
}

但是,由于SQL注入的可能性,我试图消除动态SQL。任何帮助都值得赞赏。

0 个答案:

没有答案