sqlsql-serversql-tuning

combining multiple UNION inside a view in sql server


I want to create a view as below.

Create view SomeView
AS
SELECT DISTINCT ISNULL(ID,'ID') as Id, 
ISNULL(ID,'unknown') + ':' + 'ID' AS label,
ISNULL(ID,'unknown') AS [value]
FROM [test].[emp].[OrgView]
  UNION
SELECT DISTINCT ISNULL(EMP_ID,'ID') as Id, 
ISNULL(EMP_ID,'unknown') + ':' + 'EMP_ID' AS label,
ISNULL(EMP_ID,'unknown') AS [value]
FROM [test].[emp].[OrgView]
  UNION
SELECT DISTINCT ISNULL(LICENSE_NO,'LICENSE_NO') as Id, 
ISNULL(LICENSE_NO,'unknown') + ':' + 'LICENSE_NO' AS label,
ISNULL(LICENSE_NO,'unknown') AS [value]
FROM [test].[emp].[OrgView]
.
.
.
.
.
10 such selects

So in this case, will a call be made for each select block or it will just one call ? I do not want this to make 10 different calls for each select. Please point me to some resource online if you know.


Solution

  • Unpivot using APPLY:

    SELECT DISTINCT COALESCE(v.ID, v.id_default) as Id, 
           COALESCE(o.FIRST_NAME, 'unknown') + ':' + v.name_suffix AS label,
           COALESCE(o.VALUE, 'unknown') AS [value]
    FROM [test].[emp].[OrgView] o CROSS APPLY
         (VALUES (o.ID, 'ID', 'Unknown'),
                 (o.EMP_ID, 'ID', 'EMP'),
                 (o.LICENSE, 'LICENSE_NO', 'LICENSE_NO'), . . . 
         ) v(ID, id_default, name_suffix);