title: msforeachdb with multiple queries into a single result set creating a temp table
body: <p>I am trying to run a report to get some metrics about our users and the different applications we have. Each of our customers have a different database so I need to run the same queries across several databases. The query I use works like a charm but then I need to manually copy and paste each of the results to make everything readable. So I thought I would create a temp table, then insert each query result into a different column in the table to also avoid duplicate code but somehow, most of the results returned are null or show numbers that do not much when running the query without using the temp table. Any ideas as to what I am might be doing wrong? Can't seem to figure it out</p>
  
  <pre><code>DROP TABLE #ReportAlexis
  
  CREATE TABLE #ReportAlexis
  (
      CompanyName VARCHAR(MAX),
      TotalUsers INT,
      UsersSinceDate INT,
      TotalAppUsers INT,
      AppUsersSinceDate INT,
      Number_of_Logins_SinceDate INT,
  );
  
  EXEC master.dbo.sp_msforeachdb 'if ''?'' in (''master'',''model'',''msdb'',''tempdb'') return
  declare @startdate DATETIME = ''2019-01-01''
  INSERT INTO #ReportAlexis(Companyname) Select companyname from CompanyTable where Databasename = ?;
  
  USE ?;
  INSERT INTO #ReportAlexis(TotalUsers) Select count (*) as TotalUsers from User;
  INSERT INTO #ReportAlexis(UsersSinceDate) Select count (*) as UsersSinceDate from User  where CreatedDate &gt;= @startdate;
  INSERT INTO #ReportAlexis(TotalAppUsers) Select count (*) as TotalAppUsers from Users where UserTypeID = 5;
  INSERT INTO #ReportAlexis(AppUsersSinceDate) Select count (*) as AppUsersSinceDate from Users where UserTypeID = 5 and CreatedDate &gt;=  @startdate;
  INSERT INTO #ReportAlexis(Number_of_Logins_SinceDate) Select count (*) as Number_of_Logins_SinceDate from UserLoginDetails where UserID in (Select UserID from Users where UserTypeID = 5) and LoginTime &gt;=  @startdate
  '
  SELECT * FROM #ReportAlexis
  </code></pre>