--作用:'源'表中,如果A列的记录相同的,则把B列的记录合并,再写到'目的'表中,如果不相同,则原样插入到'目的'表中
---两个原始表之一,源
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[源]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[源]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[源]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[源]
GO
CREATE TABLE [dbo].[源] (
[编号] [int] IDENTITY (1, 1) NOT NULL ,
[相同] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[不同] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
[编号] [int] IDENTITY (1, 1) NOT NULL ,
[相同] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[不同] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
---两个原始表之一,目的
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[目的]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[目的]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[目的]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[目的]
GO
CREATE TABLE [dbo].[目的] (
[编号] [int] IDENTITY (1, 1) NOT NULL ,
[相同] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[不同] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
[编号] [int] IDENTITY (1, 1) NOT NULL ,
[相同] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[不同] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
--要先按"相同"列进行排序编号,编号递增,可以不从1开始,但要连续
declare @mac varchar(100),@mac1 varchar(100),@str varchar(550),@id int,@count int,@id1 int
select @id1=编号 from 源 where 编号 in (select min(编号) from 源 )
select @count=count(*) from 源
select @str=''
select @id=@id1
while @id<@count+@id1
begin
select @mac=相同 from 源 where 编号=@id
select @mac1=相同 from 源 where 编号=@id+1
select @str=''
select @id=@id1
while @id<@count+@id1
begin
select @mac=相同 from 源 where 编号=@id
select @mac1=相同 from 源 where 编号=@id+1
if @mac=@mac1 and @id < @count+@id1-1
begin
select @str=@str+不同 from 源 where 编号=@id
select @str=@str+','
end
if @mac<>@mac1 or @id=@count+@id1-1
begin
select @str=@str+不同 from 源 where 编号=@id
insert into 目的(相同,不同) select @mac,@str
select @str=''
end
select @id=@id+1
begin
select @str=@str+不同 from 源 where 编号=@id
select @str=@str+','
end
if @mac<>@mac1 or @id=@count+@id1-1
begin
select @str=@str+不同 from 源 where 编号=@id
insert into 目的(相同,不同) select @mac,@str
select @str=''
end
select @id=@id+1
end
--truncate table 目的
转载于:https://blog.51cto.com/38641581/99827