我有两张表A和表B
一个。
channelname variablename
------------------------------
TCO1 INPUT CHANNEL
TC02 OUTPUT CHANNEL
TCO3 TEST CHANNEL
B中。
TC01 TC02 TC03
--------------------
100 443 322
200 566 990
376 453 342
45 422 856
我希望表B的输出为:
inputchannel outputchannel testchannel
---------------------------------------------
100 443 322
200 566 990
376 453 342
45 422 856
答案 0 :(得分:0)
如果您不想更改列名,则需要使用游标: 类似的东西:
Declare @sSQL as varchar(400) -- You can alway make it larger Declare @channelname as varchar(50) -- You can alway make it larger Declare @variablename as varchar(50) -- You can alway make it larger Set @sSQL='' DECLARE col_cursor CURSOR FOR select c.name, a.variablename from sys.columns c inner join sys.tables t on c.object_id = t.object_id inner join [A] as a on a.channelname = c.name where t.name = 'B' OPEN col_cursor FETCH NEXT FROM col_cursor INTO @channelname, @variablename WHILE @@FETCH_STATUS = 0 BEGIN If @sSQL='' BEGIN Set @sSQL='select [' + @channelname + ']as[' + @variablename + '] ' END ELSE BEGIN Set @sSQL= @sSQL + ',[' + @channelname + ']as[' + @variablename + '] ' END FETCH NEXT FROM col_cursor INTO @channelname, @variablename END CLOSE col_cursor DEALLOCATE col_cursor Set @sSQL= @sSQL + ' from [B]' Exec(@sSQL)
答案 1 :(得分:0)
因为人们不喜欢游标:
declare @var nvarchar(max) = N'create table ##temp ('
select @var = @var + variablename + ' varchar(max),' from TableA
set @var = LEFT(@var, LEN(@var) - 1) + ')'
execute sp_executesql @var
insert into ##temp
select * from TableB
select * into TableNew from ##temp
drop table TableB
编辑当然在删除任何表之前对此进行测试。
答案 2 :(得分:0)
根据评论:
我想创建一个查询来重命名所有列。 - 奥森 DCunha
请尝试这样的事情:
declare @columnNameFrom nvarchar(100), @columnNameTo nvarchar(100)
declare @tablename nvarchar(100)
SET @tablename = 'B'
DECLARE rename_cursor CURSOR FOR
select @tablename + '.' + c.name
, A.variablename
from syscolumns c
inner join sysobjects o on o.id = c.id
inner join A on A.channelname = c.name
where o.name = @tablename
OPEN rename_cursor
FETCH NEXT FROM rename_cursor
INTO @columnNameFrom, @columnNameTo
WHILE @@FETCH_STATUS = 0
BEGIN
SET @columnNameTo = REPLACE(@columnNameTo, ' ', '')
EXEC sp_executesql N'exec sp_rename @NameFrom, @NameTo'
, N'@NameFrom nvarchar(100), @NameTo nvarchar(100)'
, @columnNameFrom, @columnNameTo;
FETCH NEXT FROM rename_cursor
INTO @columnNameFrom, @columnNameTo
END
CLOSE rename_cursor
DEALLOCATE rename_cursor ;