Categories
Database

SQL: Insert Statement with Examples

Another technique beside selection queries in previous post, here are some of the insertion statement with example using MS SQL syntax that may help you to get understand clearer.

Insert Statement

–Subqueries help in situations when its not easy to express
–all the rows that need to be selected …… especially for
–INSERTS, UPDATES and DELETS
–In this case, I only want to see those orders that contain
–a certain product…….. in this case, ProductID=3

SELECT * FROM Orders WHERE OrderID IN ( SELECT DISTINCT OrderID FROM OrderItems WHERE ProductID=3)

INSERT Customers (FirstName, LastName, Address, City, StatePriovince, PostalCode, Country) VALUES ( ‘Bob’, ‘Tabor’, ‘1201 Wheatfield Dr.’, ‘Mesquite’, ‘TX’, ‘75088’, ‘USA’)

–UPDATES ARE THE MOST POTENTIALLY DESTRUCTIVE OF ALL
–THE SQL COMMANDS .. USE WITH EXTREME CAUTION!
–If you leave off the WHERE clause, you are in BIG trouble.
–And for this reason, NEVER perform an UPDATE or DELETE
–without first writing a SELECT statement to double
–check your WHERE clause !!!
–OR BETTER YET ….
–Make a copy of database, test your changes on the copy,
–script the SQL, make sure it works, then apply to the live database.

SELECT * FROM Customers WHERE LastName = ‘Tabor’

UPDATE Customers SET City= ‘Rowlett’, PostalCode = ‘75088’ WHERE LastName = ‘Tabor’

SLECT * FROM Customers

–SELECT * FROM Customers WHERE LastName = ‘Tabor’
DELETE Customers WHERE LastName = ‘Tabor’

–Try to delete a customer that already has an associated order
–DELETE Customers WHERE CustomerID =1
–Notice that the foreign key constraint prevents this from happening
–and creating “orphaned”rows.

SELECT * FROM Customers WHERE CustomerID =1

DELETE Customers WHERE CustomerID =1

CREATE PROCEDURE CustomerInsert
@FirstName varchar(50),
@LastName varchar(50),
@Address varchar(50),
@City varchar(50),
@StateRegion varchar(50),
@PostalCode varchar(50),
@Country varchar(50)
AS
BEGIN
INSERT Customers (FirstName, LastName, Address, City, StateRegion, PostalCode, Country)
VALUES (@FirstName, @LastName, @Address, @City, @StateRegion, @PostalCode, @Country)
END
GO

By sysomeho

Ho Sysome obtains B.S. degree in Computer Science from Phnom Penh Internation University (PPIU) in 2013 and currently studying Master of Science in IT (MSIT) at Asia Euro University (AEU). He worked as an IT Officer at Microfinance Institute and Bank in Phnom Penh. He is familar in programming language such as VB.NET, Java (Java2EE, Spring), Codeigniter, Laravel, mysql, sql server and so on. He enjoys sharing knowledges, learns from other, and develop himself.
Find him on Facebook: Spy Ro, Linkedin: Sysome HO.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.