Selecting multiple columns into a single variable.

mike55

Well-known member
Joined
Mar 26, 2004
Messages
726
Location
Ireland
Hi

Need to select multiple columns in a row into a single variable, example - persons address: line 1, line 2, line3, town, county, country as myAddress.

Any suggestions?

Mike55.
 
Found a solution, not sure if it is the best solution, would appreciate it if some one could say it is or it isnt the best solution.

Code:
SELECT ( column1 + ,  + column2 + ,  + column3) as Exp1
FROM Table1
 
What are you doing with the result then? If this is a VB or ASP.NET app then its easy to read results into a string. However if you want to have a direct Expr in SQL statement then your way is a possibility. But perhaprs something could be done with Aliases?
 
Code:
SELECT CONCAT(column1, ", ", column2, ", ", ....) as Exp1
FROM Table1

This will NOT throw an error if one of the fields happens to be numerical (probably not in your case, but you never know!)
 
@mike55:
If you dont need the columns separated out for any reasons, Id do it just the way you are, using + or whatever your DB uses for concatenation. You may want/need to wrap each column in case the values are null. In most databases, if you try to concatenate 2 strings and one is null, the result is null.

In SQL Server it would look like this:
Code:
SELECT IsNull(column1, ) + ,  + IsNull(column2, ) + ,  + IsNull(column3, ) as Exp1
FROM Table1

You can also use COALESCE (maybe with 2 Ls?) instead of IsNull if you prefer.

-ner
 
Back
Top