How to Concatenate Columns To CSV String?

In our Property table we have addresses in different fields.  A full address field is used for the ease of report generation.  This field is a concatenation of the different address fields.  Sometimes the fields are NULL or empty.  I use the following code to create CSV string:

select
STUFF(
coalesce(',',nullif(PROPNUM,''),'')
+ coalesce(','nullif(STREETDSC,''),'')
+ coalesce(','nullif([LOCALITY1],''),'')
+ coalesce(',',nullif([LOCALITY2],''),'')
+ coalesce(',',nullif([POSTCODE],''),'')
from tmppropertyimport

I am using COALESCE and NULLIF for this purpose.

In short COALESCE returns the first non-null expression from its parameter(s).

NULLIFF returns a null value if the two specified expressions are equal.

Lets look at how it works.

NULLIF(PROPNUM, ‘’) – returns PROPNUM if not null or not empty.  Returns NULL if PROPNUM is  NULL or empty.

‘,’ + NULLIF(PROPNUM, ‘’) – returns “,PROPNUM” if PROPNUM has data.  Returns NULL if PROPNUM is null or empty.

The result is CSV string beginning with a comma.  I get rid of that comma using STUFF(string,1,1,’’).

Thanks for this goes to Stackoverflow post:

http://stackoverflow.com/a/5235783

Casting UniqueIdentifier to Varchar

I had the following code which gave an error message:

BEGIN TRAN

declare @machienid varchar
set @machienid = cast(NEWID() as varchar)
select @machienid

ROLLBACK

 

The error message was:

Msg 8170, Level 16, State 2, Line 4
Insufficient result space to convert uniqueidentifier value to char.

The default length for varchar is 30, and there is a chance of data overflow.  UniqueIdentifer has length of 36 characters.  So by specifying the length of the varchar variable we can overcome this issue.

Thanks goes to Pinal Dave’s excellent blog about SQL:

SQL SERVER – FIX: ERROR: 8170 Insufficient result space to convert uniqueidentifier value to char