Jon Egerton Jon Egerton -4 years ago 127
SQL Question

Get column creation datatype for declaration

Is there a quick way to get a string containing the sql datatype required for a column declaration, based on column/column information in the database.

For example I'd want strings returned such as:


Obviously I can get the information required to generate this myself from
or from
and start handling those, but I wanted a (preferably MS provided) way to turn the datatype/maxlength/precision/scale information into the column declaration data type automatically.

I would guess that if there is a standard way to do this it would handle all possible data types, which would be a pain to try to cover manually.

EDIT: Sorry - It seems I've not been clear enough on what I want.

As an example, when you script a table for
in SSMS, the resulting script contains the datatypes in the formats I want. Is there a way to get these automatically?


OK: One more go:

What I want is a bit like this question:

SQL Server: Declaring variable type based on a column type

The difference is that I don't mind having to declare the variable dynamically as I'm working with dynamic SQL already.

Answer Source

I'm afraid I don't know of a proper way, but I've had a go at doing the INFORMATION_SCHEMA.Columns way. This is not pretty, but does handle database defaults, nullables, etc.

SELECT column_name + ' ' + DATA_TYPE + COALESCE('(' + CASE
                                                        WHEN DATA_TYPE = 'XML' THEN NULL
                                                        WHEN CHARACTER_MAXIMUM_LENGTH = -1 THEN 'max'
                                                        ELSE Cast(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5))
                                                      END + ')', '(' + Cast(NUMERIC_PRECISION AS NVARCHAR(5)) + ',' + Cast(NUMERIC_SCALE AS NVARCHAR(5)) + ')', '') + ' ' + CASE IS_NULLABLE
                                                                                                                                                                              WHEN 'YES' THEN 'NULL'
                                                                                                                                                                              ELSE 'NOT NULL'
                                                                                                                                                                            END + COALESCE(' DEFAULT' + COLUMN_DEFAULT, '')
WHERE  table_name = 'mytable'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download