小编Jay*_*hah的帖子

@parameter IS NULL 会减慢查询的执行速度吗?

选项1:

CREATE PROCEDURE [dbo].[GetStudents]
@MinimumAge int = NULL
AS

select * from Students s where @MinimumAge is null or s.Age >= @MinimumAge
Run Code Online (Sandbox Code Playgroud)

选项2:

CREATE PROCEDURE [dbo].[GetStudents]
@MinimumAge int = NULL
AS

IF @MinimumAge IS NULL
BEGIN
    select * from Students s
END
ELSE
BEGIN
    select * from Students s where s.Age >= @MinimumAge
END
Run Code Online (Sandbox Code Playgroud)

选项 1 会因为有额外的WHERE子句而比选项 2 慢吗?或者 SQL Server 会处理这个问题吗?

我认为选项 1 很好,因为我不必重复代码,除非它速度较慢。原来的程序有很多行代码。因此,我不想仅针对一种条件重复所有代码,除非这是唯一的好选择。

该列有索引age,并且不允许空值。

问题是,实际 SP 有很多行代码 - 所以我不想复制所有代码只是为了添加一个 where 条件,除非这是唯一好的选择。

performance null sql-server stored-procedures query-performance

3
推荐指数
1
解决办法
5559
查看次数