SQL Server-查询的返回列类型

时间:2018-08-02 17:05:43

标签: sql sql-server

给出一个查询,我想返回一个信息行,该信息行显示返回的每一列的类型。

我使用以下方法进行了研究:

SELECT system_type_name 
FROM 
sys.dm_exec_describe_first_result_set
('select * from table', NULL, 0) ;

这给出了我想要的简单选择语句:

enter image description here

但是当我将其用于select语句时,会出现以下错误:

enter image description here

有哪些替代方法可获取查询结果集的列?

1 个答案:

答案 0 :(得分:1)

我认为您需要在其中两个查询的下面

关于数据类型和长度

 use yourdatabasename;



 SELECT c.name AS 'Column Name',
       t.name + '(' + cast(c.max_length as varchar(50)) + ')' As 'DataType',
       case 
         WHEN  c.is_nullable = 0 then 'null' else 'not null'
         END AS 'Constraint'
  FROM sys.columns c
  JOIN sys.types t
    ON c.user_type_id = t.user_type_id
   WHERE c.object_id    in ( Object_id('ordertable'), Object_id('Course'))

---这里的订单表,当然是两个表名


SELECT 
    c.name 'Column Name',
    t.Name 'Data type',
    c.max_length 'Max Length',
    c.precision ,
    c.scale ,
    c.is_nullable,
    ISNULL(i.is_primary_key, 0) 'Primary Key'
FROM    
    sys.columns c
INNER JOIN 
    sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN 
    sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN 
    sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
    c.object_id = OBJECT_ID('YourTableName')