开发者

SQL server SP : @Param 's with sometime NULL values

开发者 https://www.devze.com 2022-12-13 15:19 出处:网络
I am very new to SQL Server Stored Procedures, I am trying to create a SP that will giv开发者_运维百科e return a list of records in a table by filter via StartDate and EndDate , but there will be \'Vi

I am very new to SQL Server Stored Procedures, I am trying to create a SP that will giv开发者_运维百科e return a list of records in a table by filter via StartDate and EndDate , but there will be 'View All' Option so sometime those @Param might not contain any values.

Currently my SP is Like

CREATE PROCEDURE [dbo].[spGetBonusRun]
 (
@StartDate as DATETIME,
@EndDate as DATETIME
 )
AS

SELECT [Id]
  ,[StartDateTime]
  ,[EndDate]
  ,[Status]
FROM [Valt].[dbo].[BonusRun]
WHERE StartDateTime <= @StartDate AND EndDate >= @EndDate

How to active that ?


Try this:

WHERE (StartDateTime <= @StartDate OR @StartDate IS NULL) AND (EndDate >= @EndDate OR @EndDate IS NULL)

Hope it helps.

/Klaus


You can try something like this

CREATE PROCEDURE [dbo].[spGetBonusRun]
 (
@StartDate as DATETIME,
@EndDate as DATETIME
 )
AS

SELECT [Id]
  ,[StartDateTime]
  ,[EndDate]
  ,[Status]
FROM [Valt].[dbo].[BonusRun]
WHERE   StartDateTime <= ISNULL(@StartDate, StartDateTime)
AND     EndDate >= ISNULL(@EndDate, EndDate)

Note the use of ISNULL

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号