Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. The problem is the 'extra' fields that need to be understood, such as NUMERIC_PRECISION and NUMERIC_SCALE.

Obviously, I can ignore the columns for INTEGER (precision of 10 and scale of 0), but there are other types I would be interested in, such as NUMERIC. So without writing lots of code to parse the table, any ideas on how to get a sort of field shorthand out of the column definition?

I would like to be able to get something like : int, datetime, money, numeric**(10,2)**

like image 976
Simon Munro Avatar asked Dec 09 '22 22:12

Simon Munro


2 Answers

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
like image 120
GalacticCowboy Avatar answered May 16 '23 04:05

GalacticCowboy


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
like image 26
Tim Lehner Avatar answered May 16 '23 03:05

Tim Lehner