注册 登录
编程论坛 ASP.NET技术论坛

数据库中表之间的转换怎么做

Bladehanyuan 发布于 2013-06-22 10:23, 588 次点击
表一
       A    B    C
I      1    2    3

II     4    5    6

III    7    8    9
怎么转换成表二

序号  C1     C2    C3
1     I       A    1
2     I       B    2
3     I       C    3
4     II      A    4
5     II      B    5   
6     II      C    6
7     III     A    7
8     III     B    8
9     III     C    9
1 回复
#2
3037709572013-06-24 15:05
*****************************************************
The following is the complete code that can be
directly executed to get results what you wanted.
If you have any questions please send me a message.
*****************************************************

----------Create a table named YourTable----------
IF EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[dbo].[YourTable]') AND type in (N'U'))
DROP TABLE [dbo].[YourTable]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[YourTable](
    [ID] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
    [A] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
    [B] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
    [C] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
----------insert data into YourTable----------
Delete From [dbo].[YourTable]
GO

Insert Into YourTable(ID,A,B,C) Values('I','1','2','3')
GO

Insert Into YourTable(ID,A,B,C) Values('II','4','5','6')
GO

Insert Into YourTable(ID,A,B,C) Values('III','7','8','9')
GO
----------To see the YourTable data------
select ID,A,B,C from [dbo].[YourTable]
------To see the converted table data-----
declare @ID varchar(50)
declare @A varchar(50)
declare @B varchar(50)
declare @C varchar(50)
declare @Table TABLE(C1 varchar(50),C2 varchar(50),C3 varchar(50))
declare ABC_Cursor cursor scroll for
SELECT ID,A,B,C  FROM [dbo].[YourTable]
open ABC_Cursor
fetch next from ABC_Cursor into @ID,@A,@B,@C
while(@@fetch_status=0)
begin
    insert into @Table(C1,C2,C3) values(@ID,'A',@A)
    insert into @Table(C1,C2,C3) values(@ID,'B',@B)
    insert into @Table(C1,C2,C3) values(@ID,'C',@C)
    fetch next from ABC_Cursor into @ID,@A,@B,@C
end
Close ABC_Cursor
deallocate ABC_Cursor
select * from @Table
Go
------------------End---------------------
Resuts:
只有本站会员才能查看附件,请 登录



[ 本帖最后由 303770957 于 2013-6-26 09:10 编辑 ]
1