I'd recommend to read this:
EXISTS (Transact-SQL)[
^]
[EDIT]
If you would like to return
NULL
, you can use this trick:
SELECT TOP(1) Field1, Field2, Field3
FROM YourTable
WHERE UserName = 'Whatever'
UNION ALL
SELECT NULL AS Field1, NULL AS Field2, NULL As Field3
But - i do NOT recommend to do such a thing for several reason...
Here's a 'working' example:
DECLARE @t TABLE (uName VARCHAR(30))
INSERT INTO @t (uName)
VALUES('A'), ('B'), ('C')
SELECT TOP(1) uName
FROM @t
WHERE uName = 'D'
UNION ALL
SELECT NULL AS uName
[EDIT 2]
According to our discussion, a
LEFT JOIN
is doing exactly what you do expect to achieve. See:
DECLARE @tmp TABLE (uName VARCHAR(30))
INSERT INTO @tmp (uName)
VALUES('A'), ('B'), ('C')
DECLARE @orig TABLE (uName VARCHAR(30), [role] VARCHAR(30))
INSERT INTO @orig (uName, [role])
VALUES('A', 'admin'), ('D', 'user'), ('C', 'user')
SELECT t.uName AS TmpName, o.*
FROM @tmp t LEFT JOIN @orig o ON t.uName = o.uName
Result:
TmpName uName role
A A admin
B NULL NULL
C C user
For further details, please see:
Visual Representation of SQL Joins[
^]