How do I return the SQL data types from my query?

前端 未结 13 1458
耶瑟儿~
耶瑟儿~ 2021-01-29 23:58

I\'ve a SQL query that queries an enormous (as in, hundreds of views/tables with hard-to-read names like CMM-CPP-FAP-ADD) database that I don\'t need nor want to understand. Th

相关标签:
13条回答
  • 2021-01-30 00:31

    You can also use...

    SQL_VARIANT_PROPERTY()
    

    ...in cases where you don't have direct access to the metadata (e.g. a linked server query perhaps?).

    • SQL_VARIANT_PROPERTY (Transact-SQL)

    In SQL Server 2005 and beyond you are better off using the catalog views (sys.columns) as opposed to INFORMATION_SCHEMA. Unless portability to other platforms is important. Just keep in mind that the INFORMATION_SCHEMA views won't change and so they will progressively be lacking information on new features etc. in successive versions of SQL Server.

    0 讨论(0)
  • You could also insert the results (or top 10 results) into a temp table and get the columns from the temp table (as long as the column names are all different).

    SELECT TOP 10 *
    INTO #TempTable
    FROM <DataSource>
    

    Then use:

    EXEC tempdb.dbo.sp_help N'#TempTable';
    

    or

    SELECT * 
    FROM tempdb.sys.columns 
    WHERE [object_id] = OBJECT_ID(N'tempdb..#TempTable');
    

    Extrapolated from Aaron's answer here.

    0 讨论(0)
  • 2021-01-30 00:34
    select COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH 
    from INFORMATION_SCHEMA.COLUMNS 
    where TABLE_NAME='yourTable';
    
    0 讨论(0)
  • 2021-01-30 00:35
    select * from information_schema.columns
    

    could get you started.

    0 讨论(0)
  • 2021-01-30 00:40

    For SQL Server 2012 and above: If you place the query into a string then you can get the result set data types like so:

    DECLARE @query nvarchar(max) = 'select 12.1 / 10.1 AS [Column1]';
    EXEC sp_describe_first_result_set @query, null, 0;  
    
    0 讨论(0)
  • 2021-01-30 00:49

    This will give you everything column property related.

    SELECT * INTO TMP1
    FROM ( SELECT TOP 1 /* rest of your query expression here */ );
    
    SELECT o.name AS obj_name, TYPE_NAME(c.user_type_id) AS type_name, c.*  
    FROM sys.objects AS o   
    JOIN sys.columns AS c  ON o.object_id = c.object_id  
    WHERE o.name = 'TMP1';
    
    DROP TABLE TMP1;
    
    0 讨论(0)
提交回复
热议问题