我有几个查询要在客户表上运行。这些查询中的每一个都识别客户表中可能存在的数据质量问题。例如,一个查询是查找客户的年龄是否< 18,不能/不应该是这种情况。
我有一个游标,可以将每个查询逐个提取到一个变量中。
我正在努力运行这些查询并汇总结果。
DECLARE c1 CURSOR FOR SELECT [ruleQuery] FROM [dbo].[SQL_DataQuality_Rules]
OPEN rules_cursor
FETCH NEXT FROM rules_cursor INTO @rulequery
WHILE @@FETCH_STATUS = 0
BEGIN
--Help needed here to execute @rulequery which would be something like
--SELECT sum(case when age < 18 then 1 else 0 end) as 'Fail' FROM...
FETCH NEXT FROM rules_cursor INTO @rulequery
END
CLOSE c1
DEALLOCATE c1
因为我将从excel调用此过程,所以我希望在excel中的一个表中包含所有失败计数。
答案 0 :(得分:1)
假设您的每个查询都有一个包含两列的表:title,fail。您的查询只有一列(失败),但您不知道该输出失败了什么。更改让他们返回标题列。你做了什么:
示例:
DECLARE @res TABLE(title VARCHAR(256), fail INT);
DECLARE c1 CURSOR FOR SELECT [ruleQuery] FROM [dbo].[SQL_DataQuality_Rules];
OPEN rules_cursor;
DECLARE @rulequery VARCHAR(MAX);
FETCH NEXT FROM rules_cursor INTO @rulequery;
WHILE @@FETCH_STATUS = 0
BEGIN
--Query like: SELECT 'Age check' AS title, sum(case when age < 18 then 1 else 0 end) as 'Fail' FROM...
INSERT INTO @res(title,fail) EXEC (@rulequery);
FETCH NEXT FROM rules_cursor INTO @rulequery;
END
CLOSE c1;
DEALLOCATE c1;
SELECT*FROM @res;
答案 1 :(得分:0)
光标内的代码将完成您的工作。但不要忘记声明@rulequery变量
IF LEN(LTRIM(RTRIM(@rulequery)))>0
EXEC(@rulequery)