Sql-server – Create a row based on a condition (column value)

querysql server

I have a table that contains the following data;

EmpNo | GivenName | PreferredName 
---------------------------------
1     | Paris     | Paris
2     | Ashley    | Ash

I am trying to get an output where, if the GivenName and PreferredName values are same, then the row should be returned as it is, but if they are different then the row should be returned twice (if possible, the row returned twice should have a NULL in PreferredName in the first occurence and GivenName a NULL in the second). Something like this:

EmpNo | GivenName | PreferredName 
---------------------------------
1     | Paris     | Paris
2     | Ashley    | NULL
2     | NULL      | Ash

I have no idea where to begin. I tried using CASE statement and FULL OUTER JOIN to no avail. I have as well tried using the code below, and it is giving me the answer for the first part of my question:

SELECT [EmpNo]
      ,[GivenName]
      ,[PreferredName]
FROM [Emp] E
WHERE [GivenName]= [PreferredName]
UNION ALL
SELECT [EmpNo]
      ,[GivenName]
      ,[PreferredName]
FROM [Emp] 

Best Answer

You can do this with the below query:

DECLARE @Employees TABLE
(
    EmpNo INT,
    GivenName NVARCHAR(255),
    PreferredName NVARCHAR(255)
)

INSERT INTO  @Employees
VALUES (1, 'Paris', 'Paris'), (2, 'Ashley', 'Ash')

SELECT EmpNo,
    GivenName,
    PreferredName
FROM @Employees
WHERE GivenName = PreferredName
UNION ALL
SELECT EmpNo,
    GivenName,
    NULL AS PreferredName
FROM @Employees
WHERE GivenName <> PreferredName
UNION ALL
SELECT EmpNo,
    NULL AS GivenName,
    PreferredName
FROM @Employees
WHERE GivenName <> PreferredName