Thursday, February 16, 2012

checking for null statement in sql

Hi Everyone,

I have a query

select name, address, city from table1

I want to append address +'-' + city in this query . I want to show hyphen only if both address and city are not null. If name is null then I don't want to show hyphen. How can I get around this problem.

Any help will be appreciated.

Thanks,

Vinki

It depends on how you're displaying it -

Also - will there be mulitple records returned?

You could keep the query the way it is - but, based on what is returned, with each row, write a function to do that for you, display-wise only.

|||If you want to do it within your query then look at the CASE statement -see here for details. The idea is you do something like:

SELECT Name, CASE Address + City WHEN NULL THEN NULL ELSE Address + ' - ' + City END FROM Table1

You'll need to put in more conditions, but that's the basic syntax.

Another alternative is to look at user-defined functions.|||I'd suggest this:

SELECT Name, Address + ISNULL(Address + City,'','-') + City FROM Table1

I don't understand this part of your requirement, though:

vinki wrote:


If name is null then I don't want to show hyphen

No comments:

Post a Comment