Hal*_*yon 3 c# sql database sql-server stored-procedures
我想创建一个存储过程,在proc的WHERE部分有一个可选参数.我的C#代码可以传入null或此proc的有效产品ID.这里是:
declare @ProductID int
set @ProductID = null
select
*
from
Products
where
Name like '%Hasbro%'
if @ProductID is not null
begin
and ProductID = @ProductID
end
Run Code Online (Sandbox Code Playgroud)
此代码不起作用.如果产品ID为null,我希望它只查找名为'Hasbro'的产品.如果产品ID不为null,我希望它在其中查找名称为'Hasbro'的产品以及匹配产品ID.
谢谢!
更新:
这是工作代码.谢谢大家帮我搞定!
declare @ProductID int
set @ProductID = null
select
*
from
Products
where
Name like '%Hasbro%'
and (( @ProductID is null ) or ( @ProductID is not null and ProductID = @ProductID ))
Run Code Online (Sandbox Code Playgroud)
小智 6
这应该也有效......
select
*
from
Products
where
Name like '%Hasbro%' and
(
( @ProductID is null ) or
( @ProductID is not null and ProductID = @ProductID )
)
Run Code Online (Sandbox Code Playgroud)