开发者

Get data types from arbitrary sql statement in SQL Server 2008

开发者 https://www.devze.com 2022-12-25 15:33 出处:网络
Given some arbitrary SQL I would like to get the data types of the returned columns.The statement might join many 开发者_如何学JAVAtables, views, TVFs, etc.I know I could create a view based on the qu

Given some arbitrary SQL I would like to get the data types of the returned columns. The statement might join many 开发者_如何学JAVAtables, views, TVFs, etc. I know I could create a view based on the query and get the datatypes from that, hoping there's a quicker way. Only think I've been able to think of is writing a .net utility to run the SQL and examine the results, wondering if there is a TSQL answer.


i.e.

Given (not real tables just an example)

SELECT p.Name AS PersonName, p.Age, a.Account as AccountName
FROM Person as p
LEFT JOIN Account as a
    ON p.Id = a.OwnerId

I would like to have something like

PersonName: (nvarchar(255), not null)

Age: (smallInt, not null)

etc...


    /*you may have to alias some columns if they are not unique*/
    /*EDIT: added fix for 2byte nchar/nvarchar */
    SELECT top (1)  /*<your query columns here>*/ 
    INTO #tmp99
    /*<rest of your query here>*/


    SELECT 'CREATE TABLE [tablename]('  UNION ALL 
    SELECT CASE WHEN ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) = 1 THEN '' ELSE ',' END 
    + CHAR(13) + '[' + c.name + '] [' + t.name + ']' 
    + CASE WHEN c.system_type_id IN (165,167,173,175) 
           THEN CASE WHEN c.max_length <> -1
                     THEN '(' + CAST(c.max_length AS varchar(7)) + ')' 
                     ELSE '(max)' 
                     END 
           WHEN c.system_type_id IN (231,239) 
           THEN CASE WHEN c.max_length <> -1 
                     THEN '(' + CAST(c.max_length/2 AS varchar(7)) + ')' 
                     ELSE '(max)' END
           ELSE 
               CASE WHEN c.system_type_id IN (41,42,43) 
                    THEN '(' + CAST(c.scale AS varchar(7)) + ')'
                    ELSE
                        CASE WHEN c.system_type_id IN (106,108) 
                             THEN '(' + CAST(c.precisiON AS varchar(7)) + ',' + CAST(c.scale AS varchar(7)) + ')'
                             ELSE ''
                             END 
                    END
           END

    + CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END 

    FROM tempdb.sys.columns c
    JOIN tempdb..sysobjects o ON (c.object_id = o.id)
    JOIN tempdb.sys.types t ON (t.user_type_id = c.user_type_id)
    WHERE o.name LIKE '#tmp99%' 
    UNION ALL SELECT ')' 
    FOR XML PATH('')

    DROP TABLE #tmp99


i tried to achieve this aim, but it turned too hard. Let me tell how i approached it. I took SQL parser: http://www.sqlparser.com/download.php and C#. Then tried to analyze text. For simple queries it is ok, but soon it gets too compilated. The idea about view looks much simpler.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号