views:

30

answers:

2

I am very new to SQL Server Stored Procedures, I am trying to create a SP that will give 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 ?

A: 

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

astander
+1  A: 

Try this:

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

Hope it helps.

/Klaus

klausbyskov
What it I want the same with [Status] (int here).
openidsujoy