How can I get SQL Server column definition with parentheses and everything?

淺唱寂寞╮ 提交于 2019-12-03 16:34:30
Tim Lehner

Here is an update (ripoff!) of GalacticCowboy's answer to fix some issues and update for all (I think) SQL Server 2008R2 datatypes:

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
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

SMO Scripting should take care of the script generations. I believe that this is what MS uses in SQL Management Studio for script generations.

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

@YourComment - 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

This is what you asked for. Short of that, you will have to parse the info schema view results.

If you're using smo you can get both precision and scale by accessing the Properties colletion of the Column Object

Column.Property["NumericScale"].Value

Column.Property["NumericPrecision"].Value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!