Friday, February 10, 2012

Concatenating columns

Hi how would i concatenate columns from my database into one column, these are the columns im trying to concatenate;

SELECT Companies.companyName, Companies.companyAddressLine1 , Companies.companyAddressLine2 as Company, Companies.companyAddressLine3, Companies.companyTown, Companies.companyPostcode, AS COMPANY

Thank you

SELECT field1 + ' ' + field2 as FIELDNAME from table ...

The "+" is used to concatenate strings

|||

Hi thanks for responding i did the following however it is not working, can you see where i am going wrong;

SELECT Companies.companyName + ' ' + Companies.companyAddressLine1 + ' ' + Companies.companyAddressLine2 + ' '+ Companies.companyAddressLine3 + ' ' + Companies.companyTown + ' '+ Companies.companyPostcode as companyName,

|||

What exactly is not working (what is the error), and can you provide the entire SQL statement?

|||

Every other column has information in it apart from the one im trying to concatenate columns into, this is my code below;

SELECT Companies.companyName + ' ' + Companies.companyAddressLine1 + ' ' + Companies.companyAddressLine2 + ' '+ Companies.companyAddressLine3 + ' ' + Companies.companyTown + ' '+ Companies.companyPostcode as companyName, Companies.companyWebsiteURL, Products.productInfoURL, SubCategories.subCategoryName, SubCategories.subCategoryDescription, Products.productPrice FROM Companies INNER JOIN Country ON Companies.countryID = Country.countryID INNER JOIN Products ON Companies.companyID = Products.companyID AND Country.countryID = Products.countryID INNER JOIN SubCategories ON Products.subcategoryID = SubCategories.subCategoryID

|||

That probably means that one of the values included in your concatenation is null, which makes the whole thing null.

For each field that is concatenated, useisnull()

select isnull(field1, '') + ' ' + isnull(field2, '') as FieldName ...

|||

Try to check null first: ISNULL(companyAddressLine3,'') . This code means that if the column companyAddressLine3 is NULL, replace it with an empty string '' (two single quotos).

In your SELECT statement do something like: SELECT ISNULL(Companies.companyName,'')+ ' ' +ISNULL(companyAddressLine1,'')+ ' ' +ISNULL(companyAddressLine2,'')+ ' '+ISNULL(companyAddressLine3,'')+ ' ' + ISNULL(Companies.companyTown,'')+ ' '+ ISNULL(Companies.companyPostcode,'') AS companyName, ........................

|||Thank you both, it works now. Thanks alot

No comments:

Post a Comment