10

SQL query:

SELECT * 
FROM Account 
WHERE (type <>100000002 ? Id='something': Id=null)

but it shows error :

Incorrect syntax near '?'

Please help me.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Suman Banerjee
  • 1,923
  • 4
  • 24
  • 40

6 Answers6

21

This is for SQL Server. IIF is not available in SQL Server 2008 or earlier.

 SELECT * 
    FROM Account 
    WHERE 
    Id=IIF(type<> 100000002,"something",null )

If you are using SQL Server 2008 or earlier, then try this.

  SELECT * 
    FROM Account 
    WHERE (Id= CASE WHEN type <>100000002 THEN 'something'  ELSE null END)
Sal Rahman
  • 4,607
  • 2
  • 30
  • 43
Suman Banerjee
  • 1,923
  • 4
  • 24
  • 40
  • 1
    If you consider best practices you should avoid using IIF because its a function and it is slower than CASE WHEN statement – dejjub-AIS May 09 '16 at 10:09
5

You can do this :

SELECT * 
FROM Account 
where (type <>100000002 and Id='something') or (type =100000002 and id is null)

or

SELECT * 
FROM Account 
where  isnull(id,'_null_')= case when type <>100000002 then 'something' else  isnull(id,'_null_') end
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
2
SELECT * 
FROM Account 
WHERE (Id= CASE WHEN type <>100000002 THEN 'something'  ELSE null END)
Krishnraj Rana
  • 6,516
  • 2
  • 29
  • 36
1

Use the following:

SELECT * 
FROM Account 
WHERE (Id= CASE WHEN type != 100000002 THEN 'something'  ELSE null END)

or

SELECT * 
FROM Account 
WHERE (Id= CASE WHEN type <> 100000002 THEN 'something'  ELSE null END)
Developerzzz
  • 1,123
  • 1
  • 11
  • 26
1
SELECT * 
FROM Account 
where (type <>100000002 and Id='something') or (type =100000002)
System
  • 21
  • 4
0

You can use case when...then in sql please see this link http://blog.sqlauthority.com/2007/04/14/sql-server-case-statementexpression-examples-and-explanation/

Rahul
  • 37
  • 1
  • 8