2008: Initializing Table Data with Row Constructors

Well, I am just discovering this feature, mostly because I never saw it demoed at any of the sessions I have attended so far on 2008.  Not that it was kept particularly hidden, I have seen the title before, but I hadn’t tried it out, or seen the depth that they have “finally” implemented.

Tonight, I am working on my chapter where I create some tables as part of a big example, and I had the code from the 2005 version of the book (and I add the primary key to the table later in the book, as well as other constraints, so don’t judge me!):

CREATE TABLE Inventory.MovieRating (
       MovieRatingId             int NOT NULL,
       Code                           varchar(20) NOT NULL,
       Description                 varchar(200) NULL,
       AllowYouthRentalFlag bit NOT NULL
)
GO

INSERT INTO Inventory.MovieRating (MovieRatingId, Code, Description, AllowYouthRentalFlag)
VALUES (0, ‘UR’,’Unrated’,1)
INSERT INTO Inventory.MovieRating (MovieRatingId, Code, Description, AllowYouthRentalFlag)
VALUE   (1, ‘G’,’General Audiences’,1),
INSERT INTO Inventory.MovieRating (MovieRatingId, Code, Description, AllowYouthRentalFlag)
VALUES (2, ‘PG’,’Parental Guidance’,1),
INSERT INTO Inventory.MovieRating(MovieRatingId, Code, Description, AllowYouthRentalFlag)
VALUES (3, ‘PG-13′,’Parental Guidance for Children Under 13’,1),
INSERT INTO Inventory.MovieRating(MovieRatingId, Code, Description, AllowYouthRentalFlag)
VALUES (4, ‘R’,’Restricted, No Children Under 17 without Parent’,0)

(Another variety is to use:

INSERT INTO Inventory.MovieRating (MovieRatingId, Code, Description, AllowYouthRentalFlag)
SELECT 0, ‘UR’,’Unrated’,1
UNION ALL
SELECT 1, ‘G’,’General Audiences’,1
UNION ALL
SELECT 3, ‘PG-13′,’Parental Guidance for Children Under 13’,1
UNION ALL
SELECT 4, ‘R’,’Restricted, No Children Under 17 without Parent’,0

But that is not that much better (certainly a little better).  I felt for the book that using VALUES was the more “proper” way to do it.  However, now, in the 2008 edition, I obviously have to change all of the code to use the latest and greatest syntax, so I use row constructors, and this turns into:

INSERT INTO Inventory.MovieRating (MovieRatingId, Code, Description, AllowYouthRentalFlag)
VALUES (0, ‘UR’,’Unrated’,1),
       (1, ‘G’,’General Audiences’,1),
       (2, ‘PG’,’Parental Guidance’,1),
       (3, ‘PG-13′,’Parental Guidance for Children Under 13’,1),
       (4, ‘R’,’Restricted, No Children Under 17 without Parent’,0)

And it just strikes me at how…simple this is, and how readable this is.  I know I have typed the UNION ALL stuff hundreds, possibly thousands (well hundreds more like) of times in the forums over the past year and a half dummying up data for someone who was asking for help but couldn’t take the time to do it for us.