How can you perform multiple different operations using a procedure without impacting any other object?

964    Asked by DanielCameron in SQL Server , Asked on Jan 13, 2020
Answered by Rachit Gupta

For an instance you need to insert/update/ delete form a table using single procedure we can do this by, passing a parameter for the operation and perform the required task

create PROCEDURE usp_Test_Multiple_task

@p_First VARCHAR(50),

@p_Second VARCHAR(50),

@P_Operation VARCHAR(50),

@p_Result VARCHAR(50) out

AS

begin

    if( @P_Operation='Insert')

    begin

           insert into input_values

           select @p_First,@p_Second

           set @p_Result='Record inserted Successfully'

    end

    if( @P_Operation='Update')

    begin

           update input_values set col2=@p_Second

           where col1=@p_First

           set @p_Result='Record Updated Successfully'

    end

    if( @P_Operation='Delete')

    begin

           delete from input_values where col1=@p_First

           set @p_Result='Record deleted Successfully'

    end

 end

Now we will execute the procedure and check if we will get the required output or not:

Insert:

declare @p_Result VARCHAR(50)

 exec usp_Test_Multiple_task 'Data1', 'inserted:Data2','Insert' , @p_Result out

select @p_Result output_value

select * from input_values


Update:

declare @p_Result VARCHAR(50)

 exec usp_Test_Multiple_task 'Data1', 'Update:Data2','Update' , @p_Result out

select @p_Result output_value

select * from input_values


Delete

go

declare @p_Result VARCHAR(50)

 exec usp_Test_Multiple_task 'Data1', '','Delete' , @p_Result out

select @p_Result output_value

select * from input_values



Your Answer

Interviews

Parent Categories