SQL - Combine multiple fields from a table into a single column

Hello,

I'm trying to concatenate the values in multiple columns into a string in another column.

Here is some SQL:
CREATE TABLE #tmpExample ( 
    column1 varchar(255),
    column2 varchar(255),
    column3 varchar(255),
	column4 varchar(255)
);
INSERT INTO #tmpExample  
VALUES 
('1', 'A', 'B', 'C'),
('2', 'D', 'E', 'F'),
('3', 'G', 'H', 'I'),
('4', '', '4', 'ME');

ALTER TABLE #tmpExample
ADD columns2_4 varchar(255)

Open in new window


Given that data I would like to write a statement that results in the following in "columns2_4":
ABC
DEF
GHI
PIZZA4ME

I'm hungry right now and so I'm thinking ISNULL(COLUMN2, 'PIZZA').

Actually any NULL in column 2,3, or 4 should return pizza (I'm REALLY hungry).  

TIA!
LVL 1
ttist25Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Brendt HessSenior DBACommented:
Note that Row 4, column 2, is not NULL - it is an empty string, which is a different thing, and changes the code. If you want to handle both empty strings and NULLs, then add this to the end of your code:

UPDATE #tmpExample
SET columns2_4 = CONCAT(ISNULL(NULLIF(column2, ''), 'PIZZA'), ISNULL(NULLIF(column3, ''), 'PIZZA'), ISNULL(NULLIF(column4, ''), 'PIZZA'))

SELECT *
FROM #tmpExample

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ttist25Author Commented:
Great thanks Brendt!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.