【发布时间】: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。任何帮助都将不胜感激。
【问题讨论】:
-
您需要使用条件
WHERE子句,并且还需要使用默认值作为NULL而不是-1。这是一个解决方案stackoverflow.com/questions/18629132/…
标签: sql stored-procedures parameters case where