user1428798
user1428798

Reputation: 1546

conditional where Sql server

I have a query

select idpays,idannonce,idville 
from annonces

and i need to make a conditional where, where idpays=1 don't show idville null else for other idpays show idville null

How can i do this please?

regards

Upvotes: 2

Views: 100

Answers (4)

Pintu Kawar
Pintu Kawar

Reputation: 2156

If your idpays column contain NULL value:

select idpays,idannonce,idville 
from annonces
where (idpays = 1 AND idville IS NOT NULL) OR (ISNULL(idpays, 0) <> 1)

If you are looking for NOT NULL values for idpays = 1 and only NULL values for idpays <> 1.

select idpays,idannonce,idville 
from annonces
where (idpays = 1 AND idville IS NOT NULL) OR (ISNULL(idpays, 0) <> 1 AND idville IS NULL)

Upvotes: 1

David W
David W

Reputation: 10184

You don't specify what, exactly, should be displayed when idpays=1, but here's a basis for what you've asked - you can do this with a case in the SELECT which sounds more like the problem you've described rather than a where clause:

select idpays,idannounce, 
       case when idpays=1 then idville 
       else null end
  from unknowntable

EDIT based on OP comments- must admit I'm not sure I understand the OP's requirements exactly at this point:

select 
  from table
 where (idpays<>1) or
       (idpays=1 and idville not null)

Upvotes: 0

kjmerf
kjmerf

Reputation: 4345

Try using a CASE function. I don't think you need the ELSE statement at all:

SELECT idpays, iddonance,
CASE WHEN idpays = 1 THEN idville END AS idville
FROM annonces

Upvotes: 0

Jaydip Jadhav
Jaydip Jadhav

Reputation: 12309

You may looking for this

WHERE ( idpays = 1 AND idville NOT NULL) OR idpays > 1

Upvotes: 3

Related Questions