ALTER procedure [Production].[ScrapReason_search]
(
@scrapreasonid as int=null,
@startdate as datetime, @enddate as datetime
)
as
begin
select * from Production.ScrapReason
where modifieddate between @startdate and @enddate and
scrapreasonid = @scrapreasonid OR
ISNULL(@scrapreasonid, '') = ''
end
为什么将null传递给变量@scrapreasonid? 我试过上面SP的案例逻辑它没有用。我知道最后的逻辑是当@scrapreasonid值没有传递然后返回所有行。但我的问题是,如果我们在decalaration传递null。然后再次为什么它正在为执行时传递的@scrapreason变量获取其他值。我没有传递null而是传递了该参数的值。
答案 0 :(得分:1)
它使参数可选。默认情况下,当执行过程时没有值传递给参数时,将传递NULL
值
当调用该过程时,@scrapreasonid
参数不应强制传递一些值
目前,您的查询就像这样执行
where (modifieddate between @startdate and @enddate and scrapreasonid = @scrapreasonid)
OR ISNULL(@scrapreasonid, '') = ''
因为AND
的优先级高于OR
,所以首先评估它,然后评估OR,这样就不会得到任何结果。
要处理NULL
值,请尝试此操作。
select * from Production.ScrapReason
where modifieddate between @startdate and @enddate and
(scrapreasonid = @scrapreasonid OR @scrapreasonid IS NULL)
答案 1 :(得分:1)
问题“想知道为什么在声明时传递了null?”答案是,它并不意味着always参数将具有NULL。如果我们传递参数“scrapreasonid”的值,则调用此过程然后它将获取该值。如果没有传递值,它将采用我们声明的默认值,即NULL