2017-08-02 16 views
0

を渡すことは、私のsqlです:がテーブルから変数を作成し、ここに、別のテーブルを介して

if object_id('tempdb..#COLUMN_NAMES') is not null 
drop table #COLUMN_NAMES 

SELECT COLUMN_NAME AS Column_Names 
INTO #COLUMN_NAMES 
FROM information_schema.columns  
WHERE table_name = 'ssrs_sourcedata' 

----- select * from #COLUMN_NAMES ---- 


if object_id('tempdb..#DATA_QUALITY_CHECK') is not null 
drop table #DATA_QUALITY_CHECK 


SELECT 
periodenddate, 
'@Column_Name' AS Label, 
MIN(@Column_Name) AS Min_Value, 
MAX(@Column_Name) AS Max_Value, 
SUM(@Column_Name) AS Sum_Value, 
AVG(@Column_Name) AS Avg_Value, 
SUM(Case when @Column_Name IS NULL THEN 1 ELSE 0 END) AS Null_Count, 
SUM(Case when len(cast(@Column_Name AS VARCHAR)) = 0 THEN 1 ELSE 0 END) AS 
Space_Count, 
MAX(len(cast(@Column_Name AS VARCHAR))) AS max_length, 
MIN(len(cast(@Column_Name AS VARCHAR))) AS min_length 
INTO #DATA_QUALITY_CHECK  
FROM dbcrms.report.ssrs_sourcedata WHERE periodenddate = '2017-06-30' 
GROUP BY periodenddate 

はどのようにして、テーブル#column_namesから変数を作成し、データ品質チェックのテーブルを介して、それに合格し、保存しませんデータ品質チェックテーブルが得られる。また、最後の列まで最初の列を読み取るようにSQLを取得する方法もあります。 #column_namesテーブルには51個のレコードがあります。次のように

答えて

0

あなたはcurosr使用することができます。

DECLARE @Column_Name varchar(255) 
DECLARE @SQL VARCHAR(MAX) 

create table ##DATA_QUALITY_CHECK 
(
Label varchar(255), 
Min_Value int, 
Max_Value int, 
Sum_Value int, 
Avg_Value int, 
Null_Count int, 
max_length int, 
min_length int  
) 

DECLARE COLUMN_NAME_CURSOR CURSOR 
FOR 
    SELECT COLUMN_NAMES 
    FROM #COLUMN_NAMES 

OPEN COLUMN_NAME_CURSOR 

FETCH NEXT FROM COLUMN_NAME_CURSOR INTO @Column_Name 

WHILE @@FETCH_STATUS = 0 
BEGIN 
     select @sql = 'INSERT INTO ##DATA_QUALITY_CHECK 
     SELECT 
    periodenddate, 
    ' + @Column_Name + ' AS Label, 
    MIN(' + @Column_Name + ') AS Min_Value, 
    MAX(' + @Column_Name + ') AS Max_Value, 
    SUM(' + @Column_Name + ') AS Sum_Value, 
    AVG(' + @Column_Name + ') AS Avg_Value, 
    SUM(Case when ' + @Column_Name + ' IS NULL THEN 1 ELSE 0 END) AS Null_Count, 
    SUM(Case when len(cast(' + @Column_Name + ' AS VARCHAR)) = 0 THEN 1 ELSE 0 END) AS 
    Space_Count, 
    MAX(len(cast(' + @Column_Name + ' AS VARCHAR))) AS max_length, 
    MIN(len(cast(' + @Column_Name + ' AS VARCHAR))) AS min_length 

    FROM dbcrms.report.ssrs_sourcedata WHERE periodenddate = ''2017-06-30'' 
    GROUP BY periodenddate ' 
     --print @sql 
     exec(@SQL) 


    FETCH NEXT FROM COLUMN_NAME_CURSOR INTO @Column_Name 
END 

CLOSE  COLUMN_NAME_CURSOR 
DEALLOCATE COLUMN_NAME_CURSOR 
0
DECLARE @Column_Name TABLE 
(
    Column_Name varchar(500) 
) 

INSERT INTO @Column_Name (Column_Name) 
SELECT COLUMN_NAME AS Column_Names 
FROM information_schema.columns  
WHERE table_name = 'ssrs_sourcedata' 

今、あなたのクエリで、このテーブルを使用することができます。

関連する問題