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'
UNION ALL
select 2,'EmpB'
UNION ALL
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!

Labels: ,