[英]Get data types from arbitrary sql statement in SQL Server 2008
Given some arbitrary SQL I would like to get the data types of the returned columns. 给定一些任意SQL我想获取返回列的数据类型。 The statement might join many tables, 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.
该语句可能会连接许多表,视图,TVF等。我知道我可以根据查询创建一个视图并从中获取数据类型,希望有更快的方法。 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.
只考虑我能够想到的是编写一个.net实用程序来运行SQL并检查结果,想知道是否有TSQL答案。
ie 即
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) PersonName :( nvarchar(255),not null)
Age: (smallInt, not null) 年龄:( 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#.
我使用了SQL解析器: http : //www.sqlparser.com/download.php和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.
关于视图的想法看起来更简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.