Question : Using If..Else in SQL Stored Procedure

I am trying to combine 2 stored procedures into one for a webpage, but cannot get the syntax right. The attached coding shows each SP, what I want to achieve is that the WHERE condition depends on whether one of the parameters is null or not. In essence the following:-

IF @tme IS NOT NULL
WHERE SupServID = @id AND EndDate >= (GETDATE() - @tme)

ELSE
WHERE SupServID = @id

This is not correct of course, and I have tried splitting the elements up, with Begin/End etc, but it still gives error.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
CREATE PROC [dbo].[usp_WDelay] 
@id int,
@tme int
AS 
SELECT * 
FROM dbo.tblWebToursPrices 
WHERE SupServID = @id AND EndDate >= (GETDATE() - @tme)
ORDER BY EndDate ASC
GO

CREATE PROC [dbo].[usp_W] 
@id int
AS 
SELECT *
FROM dbo.tblWebToursPrices 
WHERE  SupServID = @id
GO

Answer : Using If..Else in SQL Stored Procedure

so you are going to pass a null value to your stored procedure?  if so, the isnull function can be useful, as in version 1 below.

an alternative might be to have your caller just leave off the second argument if the time is not relevant for the caller's purpose.  in this case, you would change your sp to look like version 2 below.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
version 1:
CREATE PROC [dbo].[usp_WDelay]  
@id int, 
@tme int 
AS  
SELECT *  
FROM dbo.tblWebToursPrices  
WHERE SupServID = @id AND EndDate >= (GETDATE() - isnull(@tme, getdate())) 
ORDER BY EndDate ASC 
GO 

version 2:
CREATE PROC [dbo].[usp_WDelay]  
@id int, 
@tme int = 0
AS  

if @tme <> 0
SELECT *  
FROM dbo.tblWebToursPrices  
WHERE SupServID = @id AND EndDate >= (GETDATE() - @tme) 
ORDER BY EndDate ASC  

else  
SELECT * 
FROM dbo.tblWebToursPrices  
WHERE  SupServID = @id 
GO
Random Solutions  
 
programming4us programming4us