下面是zjcxc 的批量改类型,希望能给您参考一下,我是改不出,谢谢!
--------------------------------------------------------------
批量将一个库里的所有表里的char改成nchar类型     zjcxc [原作]  
关键字   数据类型修改 
出处    
 
 /*--将所有的表中,数值类型由char,varchar改为nchar,nvarchar 的存储过程--*/  
 
/*--调用示例:  
           exec  p_set  
--*/  
if  exists  (select  *  from  dbo.sysobjects  where  id  =  object_id(N'[dbo].[p_set]')  and  OBJECTPROPERTY(id,  N'IsProcedure')  =  1)  
drop  procedure  [dbo].[p_set]  
GO  
 
create  procedure  p_set  
as  
declare  tb  cursor  for  
SELECT  sql='alter  table  ['+d.name  
           +']  alter  column  ['+a.name+']  n'  
           +b.name+'('+cast(a.length*2  as  varchar)+')'  
FROM  syscolumns  a  
           left  join  systypes  b  on  a.xtype=b.xusertype  
           inner  join  sysobjects  d  on  a.id=d.id    and  d.xtype='U'  and    d.name<>'dtproperties'  
where    
           b.name  in('char','varchar')  
           and    
           not  exists(SELECT  1  FROM  sysobjects  where  xtype='PK'  and  name  in  (  
                       SELECT  name  FROM  sysindexes  WHERE  indid  in(  
                                   SELECT  indid  FROM  sysindexkeys  WHERE  id  =  a.id  AND  colid=a.colid  
                       )))                        --主键不能修改  
order  by  d.name,a.name  
 
declare  @sql  varchar(1000)  
open  tb  
fetch  next  from  tb  into  @sql  
while  @@fetch_status  =  0  
begin  
           exec(@sql)  
           fetch  next  from  tb  into  @sql  
end  
close  tb  
deallocate  tb  
go  
 

解决方案 »

  1.   

    我想知道如何把一个库中的所有字段类型为numeric(18,0)的,字段名满足 %quantity% 的字段改为numeric(18,2)
    但是不知道如何写啊
      

  2.   

    declare  tb  cursor  for  
    SELECT  sql='alter  table  ['+d.name+'] alter column ['+a.name+'] '+b.name+'(18, 2)'  
    FROM syscolumns a left join  systypes  b  on  a.xtype=b.xusertype  
         inner join sysobjects  d  on  a.id=d.id and  d.xtype='U' and d.name<>'dtproperties'  
    where a.name like '%quantity%' and 
               a.xprec = 18 and a.xscale = 0 and  
               b.name = 'numeric' and    
               not  exists(SELECT  1  FROM  sysobjects  where  xtype='PK'  and  name  in  (  
                           SELECT  name  FROM  sysindexes  WHERE  indid  in(  
                                       SELECT  indid  FROM  sysindexkeys  WHERE  id  =  a.id  AND  colid=a.colid  
                           )))                        --主键不能修改  
    order  by  d.name,a.name  
     
    declare  @sql  varchar(1000)  
    open  tb  
    fetch  next  from  tb  into  @sql  
    while  @@fetch_status  =  0  
    begin  
               exec(@sql)  
               fetch  next  from  tb  into  @sql  
    end  
    close  tb  
    deallocate  tb