SQL server Management Studio

EmpHector

Junior Member
Aug 10, 2009
10
0
0
hi i have a problem in concatenating two different columns into a single new empty column.
i have a table as fallows
P_id Last name firstname address city New_address
1 Hansen ola Timoteivn 10 Sandnes NULL
2 Svendson Tove Borgvn 23 Sandnes NULL
3 Pettersen kari storgt 20 Stavanger NULL


in this table the column new_address is empty column i want the sql query to produce following output

P_id Last name firstname address city New_address
1 Hansen ola Timoteivn 10 Sandnes Timoteivn 10,Sandnes
2 Svendson Tove Borgvn 23 Sandnes Borgvn 23, Sandness
3 Pettersen kari storgt 20 Stavanger storgt 20,Stavanger

how to concatenate the column address and city together and put it in the column new_address....

Please help

thanks in advance ...
 

MGMorden

Diamond Member
Jul 4, 2000
3,348
0
76
Originally posted by: EmpHector
i got the answer by myself

update tablename set NewColumnName=column1 +''+column2

One minor warning here - when using the + modifier to concatenate strings, any null value for any of the columns will result in the whole thing coming out null.

Better to wrap the individual strings in the ISNULL function, which basically takes your string as the first argument and a replacement value (in the case that it is null) as the second argument.

So your query would become:

UPDATE tablename SET NewColumnName = ISNULL(column1 + ' ', '') + ISNULL(column2,'')

That way the nulls are replaced with spaces and don't make your other values null. I also usually add in the addition of the space with the value tham I'm checking, because if the value is null we don't need a space after it anyways, and since adding a space to a null is still null, then the value + ' ' becomes an empty string with no space if there's nothing to print.