简体   繁体   中英

SQL Server - return column types of query

Given a query, I want to return an information row that shows the types of each column returned.

I researched using:

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

That gives what I want for simple select statements:

在此处输入图片说明

But when using this for the select statements I want to run I get the following errors:

在此处输入图片说明

What alternatives are there for grabbing columns for results set of a query?

I think you need below two Query's one of them

for Datatype and Length

 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'))

---here ordertable,Course is two table name


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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM