如何创建一个新表格,以比例和精度从information_schema.columns的列中提取数据?

时间:2019-05-29 07:19:55

标签: sql sql-server

我正在尝试从information_schema.columns创建一个表。我需要精度和小数位,以便它对十进制数据类型有帮助。我在这里面对的问题是对于INT,我无法获得精度和小数位数。有人可以帮助我选择列吗? 例如: 我需要给出这样输出的select语句 我从表A中选择,它有3列

name varchar(10),
price decimal(5,2),
Id int,

我从查询中得到的内容

name varchar(10),
price decimal(5,2),
Id int(10,0)

当前查询:

SELECT COLUMN_NAME +' ' + DATA_TYPE + ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','') + ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')+ISNULL(','+CAST(NUMERIC_SCALE)AS VARCHAR)+')','')+',' FROM INFORMATION_SCHEMA.COLUMNS

2 个答案:

答案 0 :(得分:0)

尝试此操作

create table Tbl
(
    name varchar(10),
    price decimal(5,2),
    Id int
)

select 
concat(
    name,' ',
    case system_type_id 
        when 167 then 'varchar('+cast(max_length as varchar(10))+'), ' 
        when 106 then 'decimal('+cast(precision as varchar(10))+','+cast(scale as varchar(10))+'), '
        when 56 then 'int, ' 
        --add more case for more datatype
    else '' end
    )
From sys.columns 
where object_id=(select object_id from sys.tables where name='tbl')

答案 1 :(得分:0)

这对我有用

SELECT COLUMN_NAME +' ' + DATA_TYPE + 

case DATA_TYPE when 'VARCHAR'  then

ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','')
+ ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')
+ ISNULL(','+CAST(NUMERIC_SCALE AS VARCHAR)+')','')+','

 when 'nVARCHAR'  then

ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','')
+ ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')
+ ISNULL(','+CAST(NUMERIC_SCALE AS VARCHAR)+')','')+','

when 'decimal'  then

ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','')
+ ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')
+ ISNULL(','+CAST(NUMERIC_SCALE AS VARCHAR)+')','')+','

else
''
end 

FROM INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME='A'

但是如果您的案件超过我的行情,您应该添加案件