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


当前回答

使用这个查询

SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TABLE_NAME'
ORDER BY ORDINAL_POSITION

其他回答

USE [YourDatabaseName]
GO

SELECT column_name 'Column Name',
data_type 'Data Type'
FROM information_schema.columns
WHERE table_name = 'YourTableName'
GO

这将返回值Column Name,显示列的名称,以及这些列的数据类型(int, varchars等)。

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

SHOW COLUMNS FROM `tbl_name`;

在dev.mysql.com上显示列

否则你应该能做到

DESCRIBE `tbl_name`;

MS SQL的另一个选项是用你想要的类型的查询替换这里的选择查询:

declare @sql varchar(4000);

set @sql = 'select ''hi'' as greeting';

select * from master.sys.dm_exec_describe_first_result_set (@sql, Null, 0);

使用此查询获取Schema, Table, Column,Type, max_length, is_nullable

SELECT QUOTENAME(SCHEMA_NAME(tb.[schema_id])) AS 'Schema'
    ,QUOTENAME(OBJECT_NAME(tb.[OBJECT_ID])) AS 'Table'
    ,C.NAME as 'Column'
    ,T.name AS 'Type'
    ,C.max_length
    ,C.is_nullable
FROM SYS.COLUMNS C INNER JOIN SYS.TABLES tb ON tb.[object_id] = C.[object_id]
    INNER JOIN SYS.TYPES T ON C.system_type_id = T.user_type_id
WHERE tb.[is_ms_shipped] = 0
ORDER BY tb.[Name]

对于SQL Server,这个系统存储过程将返回所有表信息,包括列数据类型:

exec sp_help YOURTABLENAME