4

我需要一种聪明的方法,以一种可以在 CREATE TABLE 语句中使用的方式从 INFORMATION_SCHEMA.COLUMNS 中获取数据类型。问题是需要理解的“额外”字段,例如 NUMERIC _PRECISION 和 NUMERIC _SCALE。

显然,我可以忽略 INTEGER 的列(精度为 10,小数位数为 0),但还有其他类型我会感兴趣,例如 NUMERIC。因此,无需编写大量代码来解析表,关于如何从列定义中获得一种字段速记的任何想法?

我希望能够得到类似:int、datetime、money、numeric**(10,2)**

4

4 回答 4

7
select column_type = data_type + 
    case
        when data_type like '%text' then ''
        when data_type like '%char' and character_maximum_length = -1 then '(max)'
        when character_maximum_length is not null then '(' + convert(varchar(10), character_maximum_length) + ')'
        when data_type = 'numeric' then '(' + convert(varchar(10), isnull(numeric_precision, 18)) + ', ' + 
            convert(varchar(10), isnull(numeric_scale, 0)) + ')'
        else ''
    end
,*
from information_schema.columns
于 2008-10-31T12:50:16.893 回答
5

这是GalacticCowboy 的答案的更新(盗版!),用于修复一些问题并更新所有(我认为)SQL Server 2008R2 数据类型:

select data_type + 
    case
        when data_type like '%text' or data_type in ('image', 'sql_variant' ,'xml')
            then ''
        when data_type in ('float')
            then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ')'
        when data_type in ('datetime2', 'datetimeoffset', 'time')
            then '(' + cast(coalesce(datetime_precision, 7) as varchar(11)) + ')'
        when data_type in ('decimal', 'numeric')
            then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ',' + cast(coalesce(numeric_scale, 0) as varchar(11)) + ')'
        when (data_type like '%binary' or data_type like '%char') and character_maximum_length = -1
            then '(max)'
        when character_maximum_length is not null
            then '(' + cast(character_maximum_length as varchar(11)) + ')'
        else ''
    end as CONDENSED_TYPE
    , *
from information_schema.columns
order by table_schema, table_name, ordinal_position
于 2012-06-27T20:03:41.633 回答
1

SMO 脚本应该负责脚本生成。我相信这就是 MS 在 SQL Management Studio 中用于脚本生成的东西。

http://msdn.microsoft.com/en-us/library/ms162153.aspx

@你的评论 -I need a smart way to get the data types out of INFORMATION_SCHEMA.COLUMNS in a way that could be used in a CREATE TABLE statement

这就是你所要求的。除此之外,您将不得不解析信息架构视图结果。

于 2008-10-31T12:31:27.290 回答
1

如果您使用的是 smo,则可以通过访问Column 对象的 Properties 集合来获得精度和比例

Column.Property["NumericScale"].Value

Column.Property["NumericPrecision"].Value

于 2009-01-19T10:19:21.460 回答