SQL Server 按ID执行查询或全部获取的最佳方式是什么?

jfewjypa  于 2023-01-01  发布在  其他
关注(0)|答案(3)|浏览(147)

我必须做一个查询过滤器,但我不想重复代码。我想在一个简单的查询,尽可能简单。

技术

SQL服务器v18

验收标准

按ID获取,如果ID有值(在本例中为一个记录),或者如果ID = NULL,则获取全部
我一直在尝试AND、OR、IS NOT NULL等,但我希望在最简单的查询中获得记录。
目前这是我的查询:

DECLARE @EventLogId int = null
SET @EventLogId = NULL

-- Insert statements for procedure here
SELECT 
    EL.EventLogId,
    EL.EventLogDateTime,
    EL.Username,
    EL.EventLogTypeId,
    EL.ActionTypeId,
    EL.ProfessionalId,
    EL.BioId,
    EL.[Message],
    EL.ExceptionMessage,
    EL.StackTrace,
    ELTypes.[Name] AS EventLogTypeName,
    ATypes.[Name] AS ActionTypeName
FROM 
    dbo.EventLog EL
INNER JOIN 
    EventLogType ELTypes ON ELTypes.Id = EL.EventLogTypeId
INNER JOIN 
    ActionTypes ATypes ON ATypes.ActionTypeId = EL.ActionTypeId
WHERE 
    EL.EventLogId = @EventLogId 
    AND NOT(EL.EventLogId IS NULL)

谢谢你的帮助!

p4tfgftt

p4tfgftt1#

SQL Server中的常见模式是

SELECT 
    EL.EventLogId,
    EL.EventLogDateTime,
    EL.Username,
    EL.EventLogTypeId,
    EL.ActionTypeId,
    EL.ProfessionalId,
    EL.BioId,
    EL.[Message],
    EL.ExceptionMessage,
    EL.StackTrace,
    ELTypes.[Name] AS EventLogTypeName,
    ATypes.[Name] AS ActionTypeName
FROM 
    dbo.EventLog EL
INNER JOIN 
    EventLogType ELTypes ON ELTypes.Id = EL.EventLogTypeId
INNER JOIN 
    ActionTypes ATypes ON ATypes.ActionTypeId = EL.ActionTypeId
WHERE 
    EL.EventLogId = @EventLogId OR @EventLogId IS NULL 
OPTION (RECOMPILE)

OPTION (RECOMPILE)会阻止SQL Server对这两种情况使用相同的计划,这是不好的。

qhhrdooz

qhhrdooz2#

你就差一点了:

WHERE 
    EL.EventLogId = @EventLogId 
    OR @EventLogId IS NULL

这个问题被称为“动态搜索条件”,替代方案是动态sql,当你有一些时间的时候,读一读Erland Sommarskog's excellent article关于这个的内容。

1tu0hz3e

1tu0hz3e3#

只是另一个选择... coalesce()

WHERE  EL.EventLogId = coalesce(@EventLogId,EL.EventLogId)

相关问题