我希望有人能帮忙或提供见解。我正在努力使我们审计数据库视图的方式自动化。目标是快速查看哪些视图中哪些列为空。我开始写剧本,但遇到了不同的问题。这个脚本的所有示例都运行了,但产生的结果并不是我想要的。现在有些列标题之间有空格。
因为我对这方面还比较陌生,所以我不确定自己做错了什么,甚至不确定如何获得我想要的结果。
提前感谢您的帮助!
示例1-运行但产生空值
示例2-运行但产生0,
示例3–为整个视图而不是列本身运行并生成计数(即,它给出了视图中的最大行数)。
------------------------------------
-- EXAMPLE 1:
-- Did not produce the results expected.
-- Issue is it returns all as NULL
---------------------------------------\
DROP TABLE IF EXISTS #tempColumnCount;
CREATE TABLE #tempColumnCount
(
Name VARCHAR(100),
Row_Count INT
);
Declare @SQL VARCHAR(MAX)
SET @SQL = ''
SELECT @SQL = @SQL + 'INSERT INTO #tempColumnCount SELECT ''' + c.name + ''' as Name, SUM (CASE WHEN ''' + c.name +
''' IS NULL THEN 1 END) FROM ' + schema_name(v.schema_id) + '.' + OBJECT_NAME(c.object_id) +
CHAR(13)
FROM sys.columns c
JOIN sys.views v
ON v.object_id = c.object_id AND SCHEMA_NAME(v.schema_id)='analytics'
exec (@SQL)
SELECT Name, Row_Count
FROM #tempColumnCount
---------------------------------------\
-- Example 2: Issue is it returns all as 0
---------------------------------------\
DROP TABLE IF EXISTS #tempColumnCount;
CREATE TABLE #tempColumnCount
(
Name VARCHAR(100),
Row_Count INT
);
Declare @SQL VARCHAR(MAX)
SET @SQL = ''
SELECT @SQL = @SQL + 'INSERT INTO #tempColumnCount SELECT ''' + c.name + ''' as Name, COUNT(1) - COUNT(''' + c.name +
''' ) FROM ' + schema_name(v.schema_id) + '.' + OBJECT_NAME(c.object_id) +
CHAR(13)
FROM sys.columns c
JOIN sys.views v
ON v.object_id = c.object_id AND SCHEMA_NAME(v.schema_id)='analytics'
exec (@SQL)
SELECT Name, Row_Count
FROM #tempColumnCount
---------------------------------------\
-- Example 3: Issue is it returns the the max amount of rows for each column. Which just means it returns the row count for the whole view and not the column it self.
---------------------------------------\
DROP TABLE IF EXISTS #tempColumnCount;
CREATE TABLE #tempColumnCount
(
Name VARCHAR(100),
Row_Count INT
);
Declare @SQL VARCHAR(MAX)
SET @SQL = ''
SELECT @SQL = @SQL + 'INSERT INTO #tempColumnCount SELECT ''' + c.name + ''' as Name, COUNT(''' + c.name +
''' ) FROM ' + schema_name(v.schema_id) + '.' + OBJECT_NAME(c.object_id) +
CHAR(13)
FROM sys.columns c
JOIN sys.views v
ON v.object_id = c.object_id AND SCHEMA_NAME(v.schema_id)='analytics'
exec (@SQL)
SELECT Name, Row_Count
FROM #tempColumnCount
暂无答案!
目前还没有任何答案,快来回答吧!