带有datekey的动态sql

时间:2016-11-29 22:41:08

标签: sql sql-server

我有以下SQL,但是我想为此添加一个日期键,但一直在苦苦挣扎:SQL如下

        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 (DataBaseName sysname,SchemaName sysname,TableName sysname, ColumnName sysname, 
        ColumnPosition     int 
        , NullCount int , NonNullCount int)


        select @sql += 'select DBName = '''+ quotename(TABLE_CATALOG) 
        +''',SchemaName = '''+ quotename(table_schema) +''',TableName = '''
        + quotename(table_name) + ''' , ColumnName = ''' + quotename(column_name) 
        + ''' , ColumnPosition = ''' + convert(varchar(5) , ordinal_position) 
        + ''' , CountNulls = sum(case when ' + quotename(column_name) + ' is null  
        then 1 else 0 end) , CountnonNulls = count(' + quotename(column_name) + ') 
        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 *,NullCntPercentage = (case when isnull(NullCount,0)=0 then 0 else cast((NullCount*100.0/(NullCount+NonNullCount)) as decimal(15,2)) end) 
        ,NonNullCntPercentage = (case when NonNullCount=0 then 0 else cast((NonNullCount*100.0/(NullCount+NonNullCount)) as decimal(15,2)) end)
        FROM #Nulls order by TableName,ColumnPosition

我想使用以下

添加日期键
 convert(nvarchar(11),getdate(),112)

但是一直在努力将其添加到动态sql而不是在第二阶段的输出中添加百分比

谢谢

0 个答案:

没有答案