如何使用括号和所有内容获取SQL Server列定义?

Sim*_*nro 4 sql-server types information-schema

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

显然,我可以忽略INTEGER的列(精度为10,比例为0),但还有其他类型我会感兴趣,例如NUMERIC.因此,如果没有编写大量代码来解析表,那么有关如何从列定义中获取某种字段速记的任何想法?

我希望能得到类似的东西:int,datetime,money,numeric**(10,2)**

Gal*_*boy 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
Run Code Online (Sandbox Code Playgroud)


Tim*_*ner 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
Run Code Online (Sandbox Code Playgroud)


Sti*_*ack 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

这就是你所要求的。除此之外,您将必须解析信息模式视图结果。