0

I have this simple-minded query:

select a.str_number+' '+a.str_name+' '+a.str_suffix+' '+a.str_apt AS addr from mytable

This query works as long as none of the concatenated values are not NULL. If any is null, the address does not show.

I tried this:

select IsNULL(a.str_number+' '+a.str_name+' '+a.str_suffix+' '+a.str_apt AS addr,'') from table

What I would like to accomplish is to replace NULL with empty space if the value is null but I still get no values.

0

3 Answers 3

1

This is a consequence of Ted Codd's rules for relational databases. As applied to MS SQL

Ideally, any operation working with NULL should lead to NULL. Though there were some issues in past due to which some SQLServer options are in place which decides how NULL is handled (instead of handling it the "definite" way).

  • ANSI_NULLS: If OFF, then NULL = NULL is True for the comparison. If ON (the default), NULL = NULL returns UNKNOWN (ideal situation).

  • CONCAT_NULL_YIELDS_NULL: If ON, NULLs are treated ideal way. e.g. NULL + <numValue> = NULL. If OFF, NULLs are treated in a nonstandard way such that NULL + <Value> = <Value>. (done for backward compatibility as per BOL, which says it all)

Null basically means something like: We don't know the value of this and so we shouldn't ever try to use it. I believe SQL distinguishes between null and an empty string, so I'd store an empty string "" if that is what I later want to use in concatenation.

Sign up to request clarification or add additional context in comments.

1 Comment

ISNULL each column which may contain a null value and concatenate the results.
1
SELECT 
ISNULL(a.str_number,'') + ' ' + 
ISNULL(a.str_name,'') + ' ' + 
ISNULL(a.str_suffix,'') + ' ' + 
ISNULL(a.str_apt,'') 
AS addr 
FROM mytable

Very ugly but that should do it.

Comments

0

Use COALESCE:

select a.str_number+' '+a.str_name+' '+COALESCE(a.str_suffix, '')+' '+a.str_apt AS addr from mytable

1 Comment

Yea, that's actually what I have decided to do but my worry is whether it is better to use COALESCE wholesale like you had it or to do it individually such as: <pre><code>select COALESCE(a.str_number,'')+' '+COALESCE(a.str_name,'')+' '+COALESCE(a.str_suffix, '')+' '+COALESCE(a.str_apt,'') AS addr from mytable</code></pre>. How expensive is this approach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.