我使用以下存储过程
CREATE PROCEDURE [dbo].[GetStates]
(
@p_StateId int = NULL
)
AS
SELECT
StateId AS CodeID,
StateName AS CodeName
FROM
States
WHERE
StateID = COALESCE(@p_StateID, StateID)
如果@p_StateId
为空,则返回所有行,否则如果StateId
匹配,则返回单行。
我的问题是,用SQL Server 2008做一个更优雅的方法吗?
答案 0 :(得分:5)
与NULL
的明确比较也应该有效:
SELECT StateId AS CodeID,
StateName AS CodeName
FROM States
WHERE @p_StateID IS NULL OR StateID = @p_StateID