SQL Server – Concat with NULL

Sorry I haven’t posted much lately. I got married a couple of Saturdays ago, then went on my honeymoon for a week. But I’m back now and better than ever. :D

***

I had a “duh” moment this morning as I was trying to figure out why my SQL code was returning NULL values. I had something to this effect:

SELECT firstName + ' ' + lastName FROM employees WHERE active = 1

As it turns out, if either firstName or lastName have are NULL, the concatenation will return NULL. I guess I just assumed it would treat NULL as an empty string in this case, but no such luck. Keep this in mind when storing NULL values in text fields that may need concatenation at some point.

Inserting Multiple Rows in MSSQL

While trying to find a way to insert multiple rows of data in one query using MSSQL, I found a solution on SQLAuthority.com. Their solution involves making use of the UNION ALL statement to combine multiple value statements. The example they give is:

USE YourDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

This is a great solution and works perfectly. However, I have found that it is not the easiest to remember – I have to go back to that site any time I want to use this because I just can’t remember the exact syntax. I was discussing this solution with a co-worker and he suggested we try something different:

INSERT INTO MyTable (FirstCol, SecondCol)
VALUES
('First', 1),
('Second', 2),
('Third', 3),
('Fourth', 4),
('Fifth', 5);

Sure enough, it works! Not only is it easier to write, but it’s so much easier to remember. Hopefully others will find this as useful as I did.

Welcome to Six Twenty!

Open BodyI hope you find the information on this blog useful. I get tired of searching for solutions that exist only on a cached page of a defunct forum in the corner of the interweb. I work mostly with XHTML, CSS, PHP, JavaScript (mostly MooTools), and MySQL, although I occasionally dab in ColdFusion, MSSQL, Flash, and ActionScript. Feel free to comment or contact me if you find a solution handy, incorrect, or just plain interesting. Thanks!