更改SQL Server中的所有列数据类型

cMi*_*nor 4 sql sql-server ssms

当我在SQL中导入表时,它建议使用真正的数据类型,现在我想将所有列更改为double类型 ...

是否有任何脚本可以在SQL Managment Studio中自动执行此操作

我的表是500列:

`After doing` EXECUTE sp_help traS

Col Type  Comp len Prec Scale   Nullable TrimTrailing Fixed Collation
------------------------------------------------------------------------------- 
x1  real    no  4   24      NULL    yes (n/a)   (n/a)   NULL
x2  real    no  4   24      NULL    yes (n/a)   (n/a)   NULL
x3  real    no  4   24      NULL    yes (n/a)   (n/a)   NULL
x4  real    no  4   24      NULL    yes (n/a)   (n/a)   NULL
...
x500 real   no  4   24      NULL    yes (n/a)   (n/a)   NULL
Run Code Online (Sandbox Code Playgroud)

Der*_*omm 8

以下代码将列的列放入一个名为的@cols循环表,循环遍历该表,生成一个alter table alter column语句,并为每个列执行它.

如果需要排除列,则应在NOT INinfo_schema.columns的谓词中包含这些列.

declare @cols table (i int identity, colname varchar(100))
insert into @cols
select column_name
from information_schema.COLUMNS
where TABLE_NAME = 'yourtable'
and COLUMN_NAME not in ('exclude1', 'exclude2')

declare @i int, @maxi int
select @i = 1, @maxi = MAX(i) from @cols

declare @sql nvarchar(max)

while(@i <= @maxi)
begin
    select @sql = 'alter table yourtable alter column ' + colname + ' decimal(18,4) NULL'
    from @cols
    where i = @i

    exec sp_executesql @sql

    select @i = @i + 1
end
Run Code Online (Sandbox Code Playgroud)