2016-11-28 51 views
0

我有以下SQL:SQL計數每列的所有表中的所有空的SYS表

SET NOCOUNT ON 
DECLARE @Schema NVARCHAR(100) = 'dbo' 
DECLARE @Table NVARCHAR(100) = NULL 
DECLARE @sql NVARCHAR(MAX) ='' 
IF OBJECT_ID ('tempdb..#Nulls') IS NOT NULL DROP TABLE #Nulls 

CREATE TABLE #Nulls (TableName sysname, ColumnName sysname, ColumnPosition int 
, NullCount int , NonNullCount int) 

SELECT @sql += 'SELECT '''+TABLE_NAME+''' AS TableName ,  

'''+COLUMN_NAME+''' AS ColumnName, '''+CONVERT(VARCHAR(5),ORDINAL_POSITION)+'''AS ColumnPosition,  
SUM(CASE WHEN '+COLUMN_NAME+' IS NULL THEN 1 ELSE 0 END) CountNulls , 
COUNT(' +COLUMN_NAME+') CountnonNulls FROM 
'+QUOTENAME(TABLE_SCHEMA)+'.'+QUOTENAME(TABLE_NAME)+';'+ CHAR(10) 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = @Schema AND (@Table IS NULL OR TABLE_NAME = @Table) 

INSERT INTO #Nulls 
EXEC sp_executesql @sql 

SELECT * 
FROM #Nulls 

此經過計算所有的空值我希望它的方式。不過,我想在一個目錄在每個表使用此SQL循環例如在

information.schema.table 

是否有人可以提供這樣做所需的SQL,我使用遊標完全一無所知。

謝謝

回答

1

不需要遊標。只需設置你的@TableNULL

DECLARE @Table NVARCHAR(100) = NULL

然後你WHERE條款從這個

WHERE TABLE_SCHEMA = @Schema AND TABLE_NAME = @Table

改變WHERE TABLE_SCHEMA = @Schema AND (@Table IS NULL OR TABLE_NAME = @Table)

所以整個代碼...

SET NOCOUNT ON 
DECLARE @Schema NVARCHAR(100) = 'dbo' 
DECLARE @Table NVARCHAR(100) = NULL 
DECLARE @sql NVARCHAR(MAX) ='' 
IF OBJECT_ID ('tempdb..#Nulls') IS NOT NULL DROP TABLE #Nulls 

CREATE TABLE #Nulls (TableName sysname, ColumnName sysname, ColumnPosition int 
, NullCount int , NonNullCount int) 

SELECT @sql += 'SELECT '''+TABLE_NAME+''' AS TableName ,  

'''+COLUMN_NAME+''' AS ColumnName, '''+CONVERT(VARCHAR(5),ORDINAL_POSITION)+'''AS ColumnPosition,  
SUM(CASE WHEN '+COLUMN_NAME+' IS NULL THEN 1 ELSE 0 END) CountNulls , 
COUNT(' +COLUMN_NAME+') CountnonNulls FROM 
'+QUOTENAME(TABLE_SCHEMA)+'.'+QUOTENAME(TABLE_NAME)+';'+ CHAR(10) 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = @Schema AND (@Table IS NULL OR TABLE_NAME = @Table) 

INSERT INTO #Nulls 
EXEC sp_executesql @sql 

SELECT * 
FROM #Nulls 
+0

'和COALESCE(@ Table,TABLE_NAME)= TABLE_NAME'或'AND NULLIF(@ Table,TABLE_NAME)= TABLE_NAME' – Hogan

+0

我收到錯誤:Msg 156,Level 15,State 1,Line 406 語法附近的語法錯誤關鍵字'列'。 Msg 156,Level 15,State 1,Line 412 關鍵字'列'附近的語法不正確。 – abs786123

+0

@ abs786123你還改變了什麼? – scsimon

相關問題