代码之家  ›  专栏  ›  技术社区  ›  Simon Munro

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

  •  4
  • Simon Munro  · 技术社区  · 16 年前

    _ 精度和数值 _ 规模

    显然,我可以忽略INTEGER的列(精度为10,刻度为0),但我还对其他类型感兴趣,例如NUMERIC。因此,在不编写大量代码来解析表的情况下,有没有关于如何从列定义中获得某种字段速记的想法?

    我希望能够得到如下信息: 日期时间, 钱 数字**(10,2)**

    4 回复  |  直到 12 年前
        1
  •  7
  •   GalacticCowboy    16 年前
    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
    
        2
  •  5
  •   Community CDub    8 年前

    这里是一个更新(抄袭!) GalacticCowboy's answer 要解决某些问题并更新所有(我认为)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
    
        3
  •  1
  •   StingyJack    16 年前

    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

    这就是你要的。除此之外,还必须解析info模式视图结果。

        4
  •  1
  •   Vitor Silva    16 年前

    如果您使用smo,则可以通过访问的属性集合来获得精度和比例 Column Object

    Column.Property[“NumericScale”]值

    Column.Property[“NumericPrecision”].Value