INFORMATION_SCHEMA.columns不会列出两列

时间:2014-06-26 15:22:03

标签: sql sql-server

我有以下代码,它应该显示列名,数据类型,大小,填充列数和总行数。

我遇到的问题是使用INFORMATION_SCHEMA.columns我只能显示DATA_TYPECHARACTER_MAXIMUM_LENGTH。如果我尝试SELECT我都会收到错误:

  

在预期条件的上下文中指定的非布尔类型的表达式,靠近'si'。

代码声明是:

DECLARE @TableName VARCHAR(512) = 'state';
DECLARE @SQL VARCHAR(1024);

WITH SQLText AS (
    SELECT 
    ROW_NUMBER() OVER (ORDER BY c.Name) AS RowNum,
    'SELECT ''' + c.name + ''', 
    MAX(b.DATA_TYPE) AS ''Data Type'', 
    SUM(CASE WHEN ' + c.Name + ' IS NULL THEN 0 ELSE 1 END) AS ''Filled Values'', 
    COUNT(*) AS ''Total Records'' 
    FROM INFORMATION_SCHEMA.columns b 
    JOIN ' + @TableName + ' ON b.column_name = ''' + c.name +'''' AS SQLRow
FROM 
    sys.tables t 
    INNER JOIN sys.columns c ON c.object_id = t.object_id
    JOIN sys.types a ON c.user_type_id = a.user_type_id
WHERE 
    t.name = @TableName)

有关如何同时展示的任何想法?

1 个答案:

答案 0 :(得分:0)

DECLARE @TableName VARCHAR(512) = 'Settings';
DECLARE @SQL VARCHAR(1024);

WITH SQLText AS (
    SELECT 
    ROW_NUMBER() OVER (ORDER BY c.Name) AS RowNum,
    'SELECT ''' + c.name + ''', 
    MAX(b.DATA_TYPE) AS ''Data Type'', 
    Max(b.CHARACTER_MAXIMUM_LENGTH) as ''CHARACTER_MAXIMUM_LENGTH'',
    SUM(CASE WHEN ' + c.Name + ' IS NULL THEN 0 ELSE 1 END) AS ''Filled Values'', 
    COUNT(*) AS ''Total Records'' 
    FROM INFORMATION_SCHEMA.columns b 
    JOIN ' + @TableName + ' ON b.column_name = ''' + c.name +'''' AS SQLRow
FROM 
    sys.tables t 
    INNER JOIN sys.columns c ON c.object_id = t.object_id
    JOIN sys.types a ON c.user_type_id = a.user_type_id
WHERE 
    t.name = @TableName)

    select * from SQLText

这适用于我,虽然我会添加以更好地了解列使用的大小。

SUM(CASE WHEN ' + c.Name + ' IS NULL THEN 0 ELSE Datalength(' + c.Name + ') END) AS ''Filled Values'',