Search code examples
sql-serversql-server-2008t-sqlsql-server-2008-r2sql-server-ce

How to use case statement in SQLServer Stored procedure


I have a Stored procedure like:

Create  PROCEDURE GetValidationData(
@ContextKey INT  --Input parameter ,  Key to execute Statement 
)AS
BEGIN
if (@ContextKey = 1) 
begin 
 Select * from table A......
end
if (@ContextKey = 2) 
begin
 Some another select statement ......
end
.
.
.
.
.
.
.
.
.
like n
END

@ContextKey is a parameter which execute proper Select Statement

Now I want to convert all code in CASE WHEN THEN statement how can i do this? on the basis of @ContextKey


Solution

  • Can you try this

    Create  PROCEDURE GetValidationData(
    @ContextKey INT  --Input parameter ,  Key to execute Statement 
    )AS
    BEGIN
    declare @sql nvarchar(max) 
    select @sql = case @ContextKey 
                        when 1 then 'Select * from table A'
                        when 2 then 'Select another select statement'
                        when number then 'Select other '
                    end
    execute(@sql)
    
    END