I have a Stored Procedure that calls other Stored Procedures depending on the Input parameters specified.
This is how it looks:
CREATE PROCEDURE dbo.usp_SPCaller
@Input_Param1 NVARCHAR(100) = NULL,
@Input_Param2 NVARCHAR(100) = NULL
AS
BEGIN
SET NOCOUNT ON
IF ((@Input_Param1 IS NOT NULL) AND (@Input_Param2 IS NOT NULL))
BEGIN
EXEC dbo.usp_SPWithParam1And2
END
IF ((@Input_Param1 IS NOT NULL) AND (@Input_Param2 IS NULL))
BEGIN
EXEC dbo.usp_SPWithParam1Only
END
IF ((@Input_Param1 IS NULL) AND (@Input_Param2 IS NOT NULL))
BEGIN
EXEC dbo.usp_SPWithParam2Only
END
IF ((@Input_Param1 IS NULL) AND (@Input_Param2 IS NULL))
BEGIN
EXEC dbo.usp_SPWithoutParam1And2
END
After presenting this to our lead, he advised me to use CASE STATEMENTS instead because using IF STATEMENTS is a bad idea.
I tried searching everywhere on how to use CASE STATEMENTS in the same format as I have above but to no avail. All I find is using CASE STATEMENTS together with UPDATE.
How do I use CASE STATEMENTS in SQL SERVER in a way that it looks like the above?
Try this code..
Here I am storing the procedure name (that is to be executed) in a variable named @sql
and at the end executing this variable using sp_executesql
CREATE PROCEDURE dbo.usp_SPCaller
@Input_Param1 NVARCHAR(100) = NULL,
@Input_Param2 NVARCHAR(100) = NULL
AS
BEGIN
SET NOCOUNT ON
DECLARE @sql AS NVARCHAR(MAX)
set @sql = case
when ((@Input_Param1 IS NOT NULL) AND (@Input_Param2 IS NOT NULL))
then 'dbo.usp_SPWithParam1And2'
when ((@Input_Param1 IS NOT NULL) AND (@Input_Param2 IS NULL))
then 'dbo.usp_SPWithParam1Only'
when((@Input_Param1 IS NULL) AND (@Input_Param2 IS NOT NULL))
then 'dbo.usp_SPWithParam2Only'
when ((@Input_Param1 IS NULL) AND (@Input_Param2 IS NULL))
then 'dbo.usp_SPWithoutParam1And2'
END
print @sql
EXEC sp_executesql @sql
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With