question

CullenG0 avatar image
CullenG0 asked

Select a.a if a.b = 'x' from dbo.a

Maybe I stumbled across the answer without realizing it or I'm not using the right terminology to search for the answer I need.

SELECT a.a IF a.b = 'X' else NULL
FROM dbo.a

I've tried it:

SELECT (IF a.b = 'X' SELECT a.a) AS Note
FROM dbo.a

Also with
WHERE a.b = 'X' or is NULL <Both with and without the 'or is NULL'>

Thank you in advance for your time.

selectresultset from variable
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
WRBI avatar image
WRBI answered

I'm a touch confused as your queries with IF and WHERE are not the same.

If i understand your queries correctly, your IF statement replaces with NULLs if the value isn't what you want (effectively the case statement in the below. Where as your WHERE clause attempt returns all the rows that are equal and would also return rows where the value is NULL (again replicated below). So they both do different things.

-- A temp table for testing.
CREATE TABLE #ExampleTable (
  ColumnOne VARCHAR(10),
  ColumnTwo VARCHAR(10)
);

-- Insert some test data.
INSERT INTO #ExampleTable (ColumnOne,ColumnTwo)
VALUES ('Red','Blue'), ('Red','Green'), ('Red',NULL)

-- This says whenever columntwo is blue, return column one or make it NULL.
SELECT CASE ColumnTwo WHEN 'Blue' THEN ColumnOne ELSE NULL END
FROM ExampleTable

-- This says return every row where column two is blue or null.
SELECT ColumnOne 
FROM #ExampleTable
WHERE ColumnTwo = 'Blue' or ColumnTwo IS NULL


Instead of the CASE statement, you could also use IIF

SELECT IIF(ColumnTwo = 'Blue', ColumnOne, NULL)
FROM ExampleTable

Hope the above has helped a little, like I've tried to infer, decided whether you want to replace value with NULLs (CASE & IIF) or whether you want to bring back columns that have NULLS.

MSDN References:

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.