我有一个约有420个表的数据库。所有表都有“审核”列:field1,field2,field3。
如何编写查询来检查整个数据库中任何这些审计列中是否有NULL值?
答案 0 :(得分:0)
下面应该为您做个窍门,如果需要其他输出,请尝试一下。
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256) = ''
DECLARE @ColumnName nvarchar(100)
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
-- check tables
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
-- check if above table has columns we want to check
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND COLUMN_NAME IN ('field1', 'field2', 'field3')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
-- insert into temp table if column value is null
IF @ColumnName IS NOT NULL
INSERT INTO #Results EXEC('SELECT DISTINCT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +' WHERE ' + @ColumnName + ' IS NULL ')
END
END
-- return results
SELECT ColumnName, ColumnValue FROM #Results
-- drop temp table
DROP TABLE #Results