从表创建变量并将其传递到另一个表

时间:2017-08-02 18:42:01

标签: sql sql-server-2014

这是我的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条记录。

2 个答案:

答案 0 :(得分: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  

答案 1 :(得分: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'

您现在可以在查询中使用此表。