如何从表中获取列名并在SQL Server中计算它们的空值?

时间:2017-05-24 13:34:10

标签: sql-server sql-server-2008-r2

我试过这样的东西,但没有用:

[MJSONWP] Encountered internal error running command: Error: Unable to launch WebDriverAgent because of xcodebuild failure: xcodebuild failed with code 65
at XCUITestDriver.quitAndUninstall$ (../../lib/driver.js:374:15)
at tryCatch (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:67:40)
at GeneratorFunctionPrototype.invoke [as _invoke] (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:315:22)
at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:100:21)
at GeneratorFunctionPrototype.invoke (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:136:37)
at process._tickCallback (internal/process/next_tick.js:109:7)

显然,“信息元表”没有来自myTable的数据。所以我需要某种JOIN吗?我是否需要声明一些变量并使用一些迭代?

奇怪的是,这个解决方案适用于某些表,但不适用于其他表(它计算为NULL):https://stackoverflow.com/a/24411738/8055476

1 个答案:

答案 0 :(得分:0)

首先,我创建了一个包含一些示例数据的表

IF OBJECT_ID('COuntNotNull') IS NOT NULL
    Drop Table COuntNotNull
    ;With cte(Column1 , Column2 , Column3 , Column4 )
    AS
    (
    SELECT  'X'     ,   ' X'    ,   NULL  ,    'X'    Union all
    SELECT NULL   ,   NULL  ,    'X'    ,    'X'       Union all
    SELECT NULL   ,   NULL  ,   NULL  ,   NULL  
    )

    SELECT * INTO  COUNTNOTNULL FROM cte

以下代码动态获取列名称对于给定的表并获取非空值的计数

DECLARE @DynamicColms NVARCHAR(max)
    ,@CaseDynamicColms NVARCHAR(max)
    ,@Sql NVARCHAR(max)
    ,@TableName VARCHAR(100) = 'COuntNotNull'--Here give Your TableName 

SELECT @DynamicColms = STUFF((
            SELECT ', ' + COLUMN_NAME
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_NAME = @TableName
            FOR XML PATH('')
            ), 1, 1, '')

--SELECT @DynamicColms
SELECT @CaseDynamicColms = STUFF((
            SELECT '+ ' + 'CASE WHEN ' + COLUMN_NAME + ' IS NOT NULL THEN 1 ELSE 0 END'
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_NAME = @TableName
            FOR XML PATH('')
            ), 1, 1, '')

--SELECT @CaseDynamicColms
SET @Sql = 'SELECT ' + @DynamicColms + ',' + @CaseDynamicColms + CHAR(13) + CHAR(10) + '  AS COUNT_NOT_NULL FROM ' + @TableName

PRINT @Sql

EXECUTE (@Sql)

结果

Column1 Column2 Column3 Column4   COUNT_NOT_NULL
-------------------------------------------------
X       X       NULL     X          3
NULL    NULL    X        X          2
NULL    NULL    NULL     NULL       0