SQL : INSERT SELECT













The INSERT SELECT is an INSERT statement that inserts value using a SELECT statement. The following query will insert a new customer using existing record.

INSERT INTO [dbo].[Customers]
([CustomerID],
[CompanyName]
,[ContactName]
,[ContactTitle]
,[Address]
,[City]
,[Region]
,[PostalCode]
,[Country]
,[Phone]
,[Fax])
SELECT 'OPDS',
CompanyName,
ContactName,
ContactTitle,
Address,
City,
Region,
PostalCode,
Country,
Phone,
Fax
FROM Customers
WHERE CustomerID = 'ALFKI'

Since the CustomerID field cannot be null we have to assign the value 'OPDS' as the new CustomerID for the new customer. The rest of the column values are selected from the Customer with customer id 'ALFKI'

Here is the new record as well as the 'ALFKI' customer for comparison.

Comments

Popular posts from this blog

SQL: GROUP BY And HAVING

Installing AdventureWorks Sample Databases from Microsoft

Docker : Pull The Latest CentOS Image Into A Ubuntu Server