Row Constructors in SQL Server 2008

Row Constructors in SQL Server 2008

Share on Facebook0Share on Google+0Tweet about this on TwitterShare on LinkedIn0Share on Reddit0
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!


Recommended eBooks on SQL Server:

Tuning SQL Server: eBook by SQL Server MVP Artemakis Artemiou
Tuning SQL Server: eBook by SQL Server MVP Artemakis Artemiou
Administering SQL Server: eBook by SQL Server MVP Artemakis Artemiou
Administering SQL Server: eBook by SQL Server MVP Artemakis Artemiou
Artemakis Artemiou
Artemakis Artemiou is a Senior SQL Server Architect, Author, Software Developer and a Microsoft Data Platform MVP. He has over 15 years of experience in the IT industry in various roles. Among other, via his initiative SQLEBooks.com, Artemakis authors and publishes eBooks on different topics on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA). Additionally he is the founder of the SQLArtBits initiative that aims to provide the technical community with simple, yet powerful and high-quality SQL Server tools. Currently, the highlights of these tools are DBA Security Advisor and In-Memory OLTP Simulator. Artemakis's official website can be found at aartemiou.com. Artemakis's blogs can be found at: SQLNetHub.com and TechHowTos.com.