我有一堆“检查”查询,如果一切正确,则所有计数都应为0。现在,我想创建一个查询,以将这些查询的所有计数汇总到一个列表中。
示例:
QueriesToCheck (Table with one column)
- MissingValues
- MissingGroup
- Ais0
Note: MissingValues (0 rows), MissingGroup (1 row), Ais0 (0 rows) are existing queries in the DB
Expected Output (Query with two columns):
QueryName Count
- MissingValues 0
- MissingGroup 1
- Ais0 0
Note: This is a query using the QueriesToCheck table
有人可以提示我如何开始吗?
答案 0 :(得分:0)
您可以执行以下操作
[mySlider integerValue]
答案 1 :(得分:0)
我的建议:
-首先是一个模型表以模拟您的系统视图问题
DECLARE @tbl TABLE(YourView VARCHAR(100));
INSERT INTO @tbl VALUES('[INFORMATION_SCHEMA].[COLUMNS]')
,('sys.objects');
-现在我们使用动态SQL生成
DECLARE @cmd VARCHAR(MAX)=
(
SELECT 'SELECT SUM(CountOfRows) FROM ('
+ STUFF(
(
SELECT ' UNION ALL SELECT COUNT(1) FROM ' + t.YourView
FROM @tbl t
FOR XML PATH('')
),1,10,'')
+ ') t(CountOfRows)'
);
-并执行此命令
EXEC(@cmd);
结果是将所有行计数加起来的单个值
我们创建如下语句:
SELECT SUM(CountOfRows)
FROM (SELECT COUNT(1)
FROM [INFORMATION_SCHEMA].[COLUMNS]
UNION ALL
SELECT COUNT(1)
FROM sys.objects) t(CountOfRows)
如果您在表中具有所有查询名称,则此语句将组成。最终结果是所有行计数的总和。
这可能更接近您的需求,想法是相同的:
DECLARE @cmd VARCHAR(MAX)=
STUFF(
(
SELECT ' UNION ALL SELECT ''' + t.YourView + ''' AS ViewName,COUNT(1) AS CountOfRows FROM ' + t.YourView
FROM @tbl t
FOR XML PATH('')
),1,10,'');
EXEC(@cmd);
结果
ViewName CountOfRows
[INFORMATION_SCHEMA].[COLUMNS] 171
sys.objects 161
您可以使用语法为INSERT INTO Target(<ColList>) EXEC(<statement>)
的任何现有表或表变量:
DECLARE @tbl TABLE(YourView VARCHAR(100));
INSERT INTO @tbl VALUES('[INFORMATION_SCHEMA].[COLUMNS]')
,('sys.objects');
DECLARE @cmd VARCHAR(MAX)=
STUFF(
(
SELECT ' UNION ALL SELECT ''' + t.YourView + ''' AS ViewName,COUNT(1) AS CountOfRows FROM ' + t.YourView
FROM @tbl t
FOR XML PATH('')
),1,10,'');
--Here I use a declared table variable
DECLARE @targetTable TABLE(ViewName VARCHAR(100),CountOfRows INT);
INSERT INTO @targetTable(ViewName,CountOfRows)
EXEC(@cmd);
--we read the result from this table
SELECT * FROM @targetTable;