title: Need help query in SQL Server 2008 based on conditions
body: <p>I have a question about SQL Server</p>
  
  <p>Table: <code>Emp</code></p>
  
  <pre><code>empid | empidref | Name
  ------+----------+------
   1    |  NULL    |  a
   3    |   1      |  b
   4    |   2      |  c
   2    | NULL     |  d
   5    | NULL     |  e
   6    | NULL     |  f
   8    |  7       |  g 
   7    | NULL     |  h
  10    |NULL      |aa
  </code></pre>
  
  <p>I want to merge <code>empidref</code> values in <code>empid</code> when <code>empid</code> also same value. If <code>empid</code> values are available in <code>empidref</code> table then same <code>empidref</code> values consider as empid and corresponding empidref  name need retrieve if <code>empid</code> values not available in <code>empidref</code> table then same empid values consider as empid and corresponding name need retrieve</p>
  
  <p>Based on above table I want output like below</p>
  
  <pre><code>Empid  | Name
  -------+------
  1      | b
  2      | c
  5      | e
  6      | f
  7      |g
  10     |aa
  </code></pre>
  
  <p>Please tell me how to write query to achieve this task in SQL Server </p>