求:按条件修改列名
现有一库,含数百个表,现要实现:当该库中任何一表中的一列包含“100万元”,该列名即改为“金额”,并且当有列名为“成交资金”时,即使符合查询条件(该列中包含“100万元”),也不修改该列名称(即保留该列名为“成交资金”),请问如何实现,谢谢!
[解决办法]
try this,
declare @tab varchar(100),@col varchar(100),@tsql varchar(6000)
declare ap scroll cursor for
select a.name 'tabname',b.name 'colname'
from sys.tables a
inner join sys.columns b on a.object_id=b.object_id
inner join sys.types c on b.system_type_id=c.system_type_id
where c.name in ('char','varchar','nchar','nvarchar') and b.name<>'成交资金'
open ap
fetch first from ap into @tab,@col
while(@@fetch_status<>-1)
begin
select @tsql='if exists(select 1 from ['+@tab+'] where ['+@col+'] like ''%100万元%'') '
+' exec sp_rename '''+@tab+'.'+@col+''',''金额'',''COLUMN'' '
exec(@tsql)
fetch next from ap into @tab,@col
end
close ap
deallocate ap