SQL Server Stored Procedures

A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again.

So if you have an SQL query that you write over and over again, save it as a stored procedure, and then just call it to execute it.

You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter value(s) that is passed.

Step 1.

CREATE TABLE CURDSP(ID INT IDENTITY(1,1) PRIMARY KEY, Name VARCHAR(100), Age INT, Address VARCHAR(100));

Step 2.

CREATE PROC usp_Employee_Management

(@ID INT, @Name VARCHAR(100), @Age INT, @Address VARCHAR(100), @Type VARCHAR(100))
AS
BEGIN


IF @Type = ‘SELECT
BEGIN
SELECT * FROM CURDSP;
END;


IF @Type = ‘INSERT
BEGIN
INSERT INTO CURDSP(Name,Age,Address) VALUES(@Name,@Age,@Address);
END;


IF @Type = ‘UPDATE
BEGIN
UPDATE CURDSP SET Name = @Name ,Age = @Age ,Address = @Address WHERE ID = @ID;
END;


IF @Type = ‘DELETE
BEGIN
DELETE FROM CURDSP WHERE ID = @ID;
END;


END;

Step 3.

For Select => EXEC usp_Employee_Management 0,”,0,”,’SELECT’


For Select => EXEC usp_Employee_Management 0,’Aaradhya DESHWAL’,3,’INDIA’,’INSERT’

For Select => EXEC usp_Employee_Management 2,’Aaradhya’,5,’Haryana INDIA’,’UPDATE’

For Select => EXEC usp_Employee_Management 3,”,0,”,’DELETE’

Leave a Comment