是否有SQL语句可以返回表中列的类型?


当前回答

下面的SQL脚本在我的结束完美地工作。

SELECT column_name AS 'Column Name',data_type AS 'Data Type' 
FROM information_schema.columns 
WHERE table_name = '[Table Name]'

其他回答

要检索实际声明的数据类型,例如在动态SQL To ALTER COLUMNs中使用,可以使用这样的方法:

SELECT
    TABLE_NAME, 
    COLUMN_NAME,
    DATA_TYPE
        + CASE WHEN DATA_TYPE IN ('char','nchar','varchar','nvarchar','binary','varbinary')
                    AND CHARACTER_MAXIMUM_LENGTH > 0 THEN
                 COALESCE('('+CONVERT(varchar,CHARACTER_MAXIMUM_LENGTH)+')','')
            ELSE '' END
        + CASE WHEN DATA_TYPE IN ('decimal','numeric') THEN
                COALESCE('('+CONVERT(varchar,NUMERIC_PRECISION)+','+CONVERT(varchar,NUMERIC_SCALE)+')','')
            ELSE '' END
        AS Declaration_Type,
    CASE WHEN IS_NULLABLE='NO' THEN 'NOT ' ELSE '' END + 'NULL' AS Nullable
FROM INFORMATION_SCHEMA.COLUMNS
ORDER BY 1,2

如果你正在使用MySQL,你可以试试

SHOW COLUMNS FROM `tbl_name`;

在dev.mysql.com上显示列

否则你应该能做到

DESCRIBE `tbl_name`;

如果有人觉得这个有用的话。在SQL Server中:

      sp_columns 'yourtablename'

这将给出所有列的详细信息。它提供了column_name、data_type、type_name、precision、length、iss_nullable等。

对于Spark SQL:

DESCRIBE [db_name.]table_name column_name

要在上面的答案的基础上进行构建,获得列数据类型的格式与声明列的格式相同通常是很有用的。

例如,varchar(50), varchar(max), decimal(p, s)。

这允许你这样做:

SELECT 
  [Name]         = c.[name]
, [Type]         = 
    CASE 
      WHEN tp.[name] IN ('varchar', 'char', 'varbinary') THEN tp.[name] + '(' + IIF(c.max_length = -1, 'max', CAST(c.max_length AS VARCHAR(25))) + ')' 
      WHEN tp.[name] IN ('nvarchar','nchar') THEN tp.[name] + '(' + IIF(c.max_length = -1, 'max', CAST(c.max_length / 2 AS VARCHAR(25)))+ ')'      
      WHEN tp.[name] IN ('decimal', 'numeric') THEN tp.[name] + '(' + CAST(c.[precision] AS VARCHAR(25)) + ', ' + CAST(c.[scale] AS VARCHAR(25)) + ')'
      WHEN tp.[name] IN ('datetime2') THEN tp.[name] + '(' + CAST(c.[scale] AS VARCHAR(25)) + ')'
      ELSE tp.[name]
    END
, [RawType]      = tp.[name]
, [MaxLength]    = c.max_length
, [Precision]    = c.[precision]
, [Scale]        = c.scale
, [IsNullable]   = c.is_nullable
FROM sys.tables t 
JOIN sys.schemas s ON t.schema_id = s.schema_id
JOIN sys.columns c ON t.object_id = c.object_id
JOIN sys.types tp ON c.user_type_id = tp.user_type_id
WHERE s.[name] = 'dbo' AND t.[name] = 'MyTable'