我有一个State
参数作为可选的存储过程,所以如果我通过状态它应该使用两个参数查询表,如果我没有传递状态参数我只需要用模板查询表参数。
我怎么能这样做?
这是我的存储过程:
CREATE PROCEDURE [dbo].[Get_TempName]
@TemType varchar(50),
@State varchar(50) = 'N/A'
AS
BEGIN
SET NOCOUNT ON;
SELECT
[TempType],
[TempName],
[State]
FROM
[Template] WITH (NOLOCK)
WHERE
TempType = @TempType
AND [State] = @State
END
答案 0 :(得分:2)
Create[dbo].[Get_TempName]
@TemType varchar(50)
,@State varchar(50) = NULL
AS
BEGIN
SET NOCOUNT ON;
SELECT
[TempType]
,[TempName]
,[State]
FROM [Template] WITH (NOLOCK)
where TempType = @TempType
and (([State] IS NULL) OR ([State] = @State))
END
答案 1 :(得分:1)
您可以OR
条件使用Is Null
条件。如果您不想在过滤器
NULL
,请在@state
参数中传递Create[dbo].[Get_TempName]
@TemType varchar(50)
,@State varchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT
[TempType]
,[TempName]
,[State]
FROM [Template] WITH (NOLOCK)
where TempType = @TempType
and ([State] = @State or @state is null)
END
VisitorParking
答案 2 :(得分:1)
您可以在一个select语句中执行所有操作,但这可能会对性能产生负面影响。通常最好根据参数将其分成单独的选择。
Create[dbo].[Get_TempName]
@TemType varchar(50)
,@State varchar(50)
AS
BEGIN
SET NOCOUNT ON;
IF(@State IsNull)
SELECT
[TempType]
,[TempName]
,[State]
FROM [Template] WITH (NOLOCK)
where TempType = @TempType
ELSE
SELECT
[TempType]
,[TempName]
,[State]
FROM [Template] WITH (NOLOCK)
where TempType = @TempType
and [State] = @State
END