msforeachdb,将多个查询合并到单个结果集中,以创建临时表

时间:2019-02-27 20:07:42

标签: sql-server tsql

我正在尝试生成报告,以获取有关我们的用户以及我们拥有的不同应用程序的一些指标。我们每个客户都有一个不同的数据库,因此我需要在多个数据库中运行相同的查询。我使用的查询就像一个超级按钮一样工作,但随后我需要手动复制和粘贴每个结果,以使所有内容可读。因此,我想我将创建一个临时表,然后将每个查询结果插入表中的不同列中,以避免重复代码,但是以某种方式,大多数返回的结果为null或在不使用查询运行查询时显示的数字不多临时表。关于我在做什么的任何想法可能做错了吗?似乎无法弄清楚

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 >= @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 >=  @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 >=  @startdate
'
SELECT * FROM #ReportAlexis

1 个答案:

答案 0 :(得分:0)

我假设范围已断开,请尝试使用## table(全局临时表)。尽管实名可以在以下位置找到,但#table只能在范围内轻松访问:

select t.name from tempdb.sys.tables t where t.name like '#ReportAlexis%'

/* it's still better to use a global temp table */

CREATE TABLE ##ReportAlexis
(
    CompanyName VARCHAR(MAX),
    TotalUsers INT,
    UsersSinceDate INT,
    TotalAppUsers INT,
    AppUsersSinceDate INT,
    Number_of_Logins_SinceDate INT,
);