I have a table that has records with a structure similar to this..
ID RoleID
1 NULL
2 15
3 16
I wrote a where clause to get records like the following
SELECT * from TableX
WHERE (RoleID = 2 OR RoleID IS NULL)
This gets me the record of “1,NULL”
But if i query
SELECT * from TableX
WHERE (RoleID = 15 OR RoleID IS NULL)
I get back “1,NULL” and “2,15”.
Does anyone know how to structure a select to give me only one record? I only want “2,15” if 15 was passed and “1,NULL” if there are no matches.
Note, the actual query has MANY more where clauses to it, so nesting itself inside itself would be a very big query.
How about SELECT TOP 1 with ORDER BY RoleID DESC
Here is a working example.
Edit (edited based on comments received)
Note that the Insert statement works only for SQL Server 2008. For versions prior to 2008, you will have to break it into invidual inserts.