title: Get data from different databases dynamically in sql server
body: <p>I am facing a problem in sql query. I have my databases which has same tables and same column in every table. I want to retrieve same columns from two or three tables in every database.
  ex.</p>
  
  <pre>
  <b>DatebaseName      TableName(exist in every database)</b>
  <hr/> 
  Demo               Patient, charge, WorkDescriptor
  Medical            Patient, charge, WorkDescriptor
  Test               Patient, charge, WorkDescriptor
  </pre>
  
  <p>This is my query</p>
  
  <pre>
  
  select 
  db_name() as DBName,
  substring(convert(varchar, c.eDate, 101), 0, 11) as Date,
  c.operatorID as username,
  count(wd.code) as TotalCPT,
  p.acctnumber as TotalPatient,
  sum(c.amount) as TotalAmount
  from Charge c
  inner join workDescriptor wd on wd.IDWorkDescriptor = c.WorkDescriptorID
  inner join patient p on c.PatientID = p.IDPatient
  where c.eDate between '01/01/2009' and '05/31/2011'
  group by c.operatorID, substring(convert(varchar, c.eDate, 101), 0, 11), p.acctnumber
  order by substring(convert(varchar, c.eDate, 101), 0, 11)
  compute sum(count(wd.code))
  </pre>
  
  <p>It is retreive the data of current database. But
  I want the output data from every database.
  like
  example solution</p>
  
  <pre>
  <b>DBName      Date(mm/dd/yyyy)Username  TotalCPT  TotalPatient TotalAmount</b>
  Demo           01/01/2010      A         1           1            41.82
  Demo           01/01/2010      A         5           4            70.00
  Demo           01/01/2010      B         3           3            41.84
  Medical        01/02/2010      A         1           1             0.00
  Medical        01/02/2010      B         5           4            50.24
  Medical        01/02/2010      B         3           3            21.50    
  Test           01/03/2010      A         1           1            56.98         
  Test           01/03/2010      A         5           4            45.75         
  Test           01/03/2010      B         3           3            56.52    
                                         ------     --------       ---------------
                                          27           25          384.65
  </pre>
  
  <p>Any suggestion will be appreciated. If you have any query to achieve my goal.
  Thanks in advance</p>