Row Constructors in SQL Server

In this article, we will talk about Row Constructors in SQL Server, which was originally shipped with SQL Server 2008.

 

Inserting Records to a Table Prior to the Row Constructors Feature

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.

Let’s see an example.

Create Sample Table

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

 

Code Example – Using 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 Clause

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

 

Inserting Records to a Table Using the Row Constructors Feature

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.

Let’s continue the example discussed above, but this time, using Row Constructors.

 

Check out the following code example with Row Constructors:

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

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

 

Creating a temporary table using Row Constructors

Now, check this out:

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

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!

 


Learn more tips like this!
Enroll to our Online Course!

Check our online course titled “Essential SQL Server Development Tips for SQL Developers” (special limited-time discount included in link).

Sharpen your SQL Server database programming skills via a large set of tips on T-SQL and database development techniques. The course, among other, features over than 30 live demonstrations!

Essential SQL Server Development Tips for SQL Developers - Online Course

Learn More


 

Featured Online Courses:

 

Related SQL Server Development Articles:

 

Subscribe to our newsletter and stay up to date!

Check out our latest software releases!

Check out Artemakis’s eBooks!

 

Rate this article: 1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Reference: SQLNetHub.com (https://www.sqlnethub.com)

© SQLNetHub