【问题标题】:CASE for Parameter conditions in SP WHERESP WHERE 中参数条件的 CASE
【发布时间】:2015-08-26 17:04:13
【问题描述】:

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

IF (@ComputerType > -1 OR @DriveType > -1 OR @EncryptionState > -1 OR 
@ProtectorType <> '-1' OR @CipherStrength > -1)
BEGIN -- Not ALL
-- restrict to parameter values
   SELECT computerType, ComputerName, DriveType, DriveLetter,
      Encryption, ProtectType, Cipher
   FROM computers
   WHERE 
     -- case @computertype > -1 and @computertype <> `100 then    @computertype=computerType 
    -- case @DriveType > -1 and @drivetype <> 100 then @drivetype = drivetype
    -- case @EncryptionState > -1 and @EncryptionState <> 100 then Encryption=@EncryptionState
   -- etc for each parameter


END
ELSE -- All
BEGIN
  -- select statement with no WHERE
END

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

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 注入的可能性,我正在尝试消除动态 SQL。任何帮助都将不胜感激。

【问题讨论】:

标签: sql stored-procedures parameters case where


【解决方案1】:

您可以使用 AND 和 OR 运算符完成此操作:

(case @computertype > -1 and @computertype <> 100 AND    @computertype=computerType) OR
(case @DriveType > -1 and @drivetype <> 100 AND @drivetype = drivetype) OR
(case @EncryptionState > -1 and @EncryptionState <> 100 AND Encryption=@EncryptionState)
-- etc for each parameter

【讨论】:

    【解决方案2】:

    您可以通过以下方式做到这一点(不使用 case 语句)

    WHERE (@computertype = -1 or computerType = @computertype)
    and ....
    

    显然,为每个参数添加另一个子句。

    【讨论】:

    • 你有这个倒退 - 你的 orand 应该切换。
    猜你喜欢
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多