Friday, December 19, 2008

Row Constructors in SQL Server 2008

There are many cases were we just want to insert some data to a table.
The traditional ways of doing that in SQL Server versions earlier than 2008 were by using separate insert statements for each record to be inserted or by using the UNION ALL clause.

Consider the following table:

CREATE TABLE [dbo].[employee](
[ID] [int] NOT NULL,
[Name] [varchar](50) NULL

Code Example - Separate Insert Statements:

insert into dbo.employee(id,name)
values (1,'EmpA')

insert into dbo.employee(id,name)
values (2,'EmpB')

insert into dbo.employee(id,name)
values (3,'EmpC')

Code Example - Using the UNION ALL:

insert into dbo.employee(id,name)
select 1,'EmpA'
select 2,'EmpB'
select 3,'EmpC'

Row constructors allow us to insert multiple records to a table within a single SQL Statement. To this end, records must be contained in parentheses and be separated with commas.

Check out the following code example:

insert into dbo.employee(id,name)
values (1,'EmpA'),(2,'EmpB'),(3,'EmpC')

By using one single SQL statement instead of three we get the same result!

Now check this out:

select c.empID,c.empName from
(values (1,'EmpA'),(2,'EmpB'),(3,'EmpC')) as c(empID,empName);

In the above example by using Row Constructors we created a "temporary table", defined its values and column names and performed a selection. All were done by using a single SQL Statement! That's great stuff!
Check out my latest eBook on SQL Server:
Tuning SQL Server - Ebook

Easily secure your SQL Server instances! Try out DBA Security Advisor!
DBA Security Advisor for SQL Server by SQLArtBits
DBA Security Advisor was developed by SQLArtBits. The tool was being carefully developed for an entire year and it contains comprehensive security checks and recommendations based on proven SQL Server security best practices. Feel free to download and use the Community Edition which is free and if you find it useful, you can consider upgrading to the Enterprise Edition!

Artemakis Artemiou [MVP]

Author & Editor

Artemakis Artemiou is a Senior SQL Server Architect, Software Developer and Microsoft Data Platform MVP. He is also an author, regular blogger, president of Cyprus.NET User Group and CY Country leader of INETA-EU. He is also the creator of DBA Security Advisor and In-Memory OLTP Simulator. Artemakis is a frequent guest author of worldwide well-respected online journals where he writes articles focusing on many SQL Server topics.

Reference: The SQL Server and .NET Hub (