Select Update Delete SQL Server
Select Update Delete SQL Server
Here, we will see how to create select, insert, update, delete statements using stored procedures in
SQL Server. Let's take a look at a practical example. We create a table.
Creating Table
Now add some rows to the table. We can add new rows using an INSERT INTO SQL statement.
Then execute a SELECT SQL query to display all records of the table.
go
SELECT *
FROM employee
SQL
1
Figure 1
Here, we create a stored procedure with SELECT, INSERT, UPDATE, and DELETE SQL
statements. The SELECT SQL statement is used to fetch rows from a database table. The INSERT
statement is used to add new rows to a table. The UPDATE statement is used to edit and update the
values of an existing record. The DELETE statement is used to delete records from a database
table. The following SQL stored procedure is used insert, update, delete, and select rows from a
table, depending on the statement type parameter.
IF @StatementType = 'Select'
BEGIN
SELECT *
FROM employee
END
IF @StatementType = 'Update'
BEGIN
UPDATE employee
SET first_name = @first_name,
last_name = @last_name,
salary = @salary,
city = @city
WHERE id = @id
END
ELSE IF @StatementType = 'Delete'
BEGIN
2
DELETE FROM employee
WHERE id = @id
END
END
SQL
Now press F5 to execute the stored procedure. This will create a new stored procedure in the
database.
StatementType = 'Insert'
3
Figure 2
4
Figure 3
Now for insert, we fill the data in values in the required fields.
StatementType=insert
5
Figure 4
Figure 5
6
Stored Procedure to Check update
StatementType = 'Update'
Figure 6
7
Figure 7
StatementType = 'Delete'
Figure 8
Click on the OK button. And check in the employee table with the following deleted data where id
is 2.
8
Figure 9
Summary
A single stored procedure can be used to select, add, update, and delete data from a database table.
In this article, we learned how to create a single stored procedure to perform all operations using a
single SP in SQL Server.