循环播放重命名#Temp表列

时间:2011-01-21 12:46:23

标签: sql-server temp-tables

我有一个#TempTble,看起来像这样:

Col1,Col2,5,8,19,....

另外,我有另一个表格,其描述与#TempTble中的键匹配:

key   Descr    
===   ====    
5     Descr1    
8     Descr2    
19    Descr3

这是循环#TempTble并使用匹配描述重命名列的最佳方式,因此它看起来像这样:

Col1,Col2,Descr1,Descr2,Descr3,...

提前致谢。

2 个答案:

答案 0 :(得分:3)

IF object_id('tempdb..#Temp') IS NOT NULL DROP TABLE #Temp

declare @map table ([key] sysname,Descr sysname)

INSERT INTO @map
select 5,'Descr1' UNION ALL
select 8,'Descr2' UNION ALL    
select 19,'Descr3'

create table #Temp ([Col1] int,[Col2] int,[5] int,[8] int,[19] int)

DECLARE @name nvarchar(1035), @descr sysname;

DECLARE ColumnCursor CURSOR 
LOCAL FORWARD_ONLY STATIC READ_ONLY TYPE_WARNING
FOR SELECT 'tempdb..#Temp.' + QUOTENAME(name), Descr
FROM tempdb.sys.columns 
JOIN @map m ON m.[key]=name
where object_id=object_id('tempdb..#Temp');

OPEN ColumnCursor;
FETCH NEXT FROM ColumnCursor INTO @name, @descr;
WHILE @@FETCH_STATUS = 0
BEGIN;
 EXECUTE tempdb..sp_rename @name, @descr,'COLUMN';
FETCH NEXT FROM ColumnCursor INTO @name, @descr;
END;
CLOSE ColumnCursor;
DEALLOCATE ColumnCursor;

SELECT * FROM #Temp

答案 1 :(得分:0)

这是一个糟糕的设计 一种选择是运行此代码;复制结果并再次运行

select 'exec tempdb..sp_rename ''#temp.['+t1.name+']'','''+t2.descrip+'''' 
from tempdb..syscolumns as t1 inner join mytable as t2 on t1.name=t2.[key] 
where id=OBJECT_ID('tempdb..#temp') and t1.name like '[0-9]%'