SQL WHERE子句中的CASE语句

时间:2014-11-10 15:52:54

标签: sql-server stored-procedures

最初,我在C#中构建搜索字符串并使用它来搜索数据库,但我开始将其切换为使用存储过程。我想要做的是,当@DeletedDeviceSearch变量为false时,它会将“LogicallYDeleted = 0”添加到搜索字符串中,否则它会搜索逻辑删除的设备和当前设备。

我遇到了WHERE条款的问题。我相信CASE声明是要走的路,但我不知道如何配置它...任何帮助表示赞赏

以下是代码:

USE Inventory;
GO
CREATE PROCEDURE [dbo.InventorySearch] 
    @FieldName nvarchar(50), 
    @SearchTerm nvarchar(50)
    @DeletedDeviceSearch bit
AS 
SET NOCOUNT ON;
SELECT LK_User, LK_Location, DeviceName, AssetTypeId, DeviceID, SerialNumber, LogicallyDeleted
FROM Device 
WHERE 

(CASE(@DeviceSearch) 
    WHEN 1 THEN 
        LogicallyDeleted = 0 and  @FieldName = @SearchTerm

        ELSE @FieldName = @SearchTerm)
GO

2 个答案:

答案 0 :(得分:2)

where条款中,除了case之外,还有更好的方法。您可以像这样编写where子句:

WHERE 
   (@DeviceSearch = 1 and LogicallyDeleted = 0 and @FieldName = @SearchTerm) OR
   (@DeviceSearch <> 1 and @FieldName = @SearchTerm)

但是,如果确实想要使用case语句,请注意case返回一个值,但不执行某些操作。所以必须这样读:

WHERE
  LogicallyDeleted = CASE WHEN @DeviceSearch = 1 THEN 0 ELSE LogicallyDeleted END AND
  @FieldName = @SearchTerm

这里的诀窍是LogicallyDeleted仅与@DeviceSearch = 1进行比较。在所有其他情况下,LogicallyDeleted与自身进行比较,总是返回true。

因此,如果@DeviceSearch不是1,则where子句如下所示:

WHERE LogicallyDeleted = LogicallyDeleted AND @FieldName = @SearchTerm

如果@DeviceSearch为1,则where子句如下所示:

WHERE LogicallyDeleted = 0 AND @FieldName = @SearchTerm

答案 1 :(得分:0)

因为此SP用于搜索目的(因此SPEEEED和准确性是强制性的)我会像这样创建SP内容:

IF(@DeviceSearch = 1)
BEGIN
 SELECT LK_User,LK_Location,DeviceName,AssetTypeId,DeviceID,SerialNumber,LogicallyDeleted
  来自设备
  LoghereDeleted = 0和@FieldName = @ SearchTerm
END
ELSE
BEGIN
 SELECT LK_User,LK_Location,DeviceName,AssetTypeId,DeviceID,SerialNumber,LogicallyDeleted
  来自设备
  WHERE @FieldName = @ SearchTerm
END

我知道这更难维护,选择状态&#34;看起来&#34;多余但这种方式更快..