求助一个MERGE的问题
MERGE INTO [GROUP_MEMBER] AS A
USING @MEMBER_TABLE AS B
ON (A.[CUSTOMER_ID]=B.[CUSTOMER_ID] AND A.[GROUP_ID]=@GROUP_ID)
WHEN NOT MATCHED
THEN INSERT([CUSTOMER_ID],[GROUP_ID]) VALUES(B.[CUSTOMER_ID],@GROUP_ID)
WHEN NOT MATCHED BY SOURCE
THEN DELETE;
/*
工单号 操作者
a1 张三
a1 王二
a1 李四
现在要得到查询结果:
工单号 操作者
a1 张三、王二、李四
*/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[test1]') AND type in (N'U'))
DROP TABLE [dbo].[test1]
GO
CREATE TABLE [dbo].[test1](
工单号 [varchar](10) NOT NULL,
操作者 [varchar](10) NOT NULL
) ON [PRIMARY]
GO
INSERT [test1]
VALUES ('a1','张三'),('a1','王二'),('a1','李四')
select 工单号,
操作者=stuff((select '、'+操作者
from test1
where 工单号=t.工单号
for xml path('')),1,1,'')
from test1 t
group by 工单号
DECLARE @s VARCHAR(4000)
SELECT @s=@s +'、'+操作者 from test1 WHERE 工单号='a1'
PRINT @s
SET @s=STUFF(@s,1,1,'')
EXEC('select 工单号,'+@s+' FROM test1')
create table a3
(NAME varchar(10), GNAME varchar(10))
insert into a3
select 'ZS', '分组1' union all
select 'LS', '分组1' union all
select 'WW', '分组1' union all
select 'ZS', '分组2' union all
select 'LS', '分组2' union all
select 'ZS', '分组3' union all
select 'WW', '分组3'
select a.NAME,
stuff((select ','+isnull(b.GNAME,'') from a3 b
where b.name=a.NAME for xml path('')),1,1,'') 'GNAME'
from a3 a
group by a.NAME
order by a.NAME desc
/*
NAME GNAME
---------- ------------------------
ZS 分组1,分组2,分组3
WW 分组1,分组3
LS 分组1,分组2
(3 row(s) affected)
*/
IF OBJECT_ID('GROUP_MEMBER','u') IS NOT NULL
DROP TABLE [GROUP_MEMBER]
CREATE TABLE [GROUP_MEMBER] ([GROUP_ID] int, [CUSTOMER_ID] int)
INSERT [GROUP_MEMBER] SELECT 1, 10 UNION ALL SELECT 1, 11 UNION ALL SELECT 2, 999
--sql:
DECLARE @GROUP_ID INT
SET @GROUP_ID = 1
DECLARE @MEMBER_TABLE TABLE([CUSTOMER_ID] int)
INSERT @MEMBER_TABLE SELECT 11 UNION ALL SELECT 12
--data:
SELECT * FROM [GROUP_MEMBER]
SELECT * FROM @MEMBER_TABLE
MERGE INTO [GROUP_MEMBER] AS A
USING @MEMBER_TABLE AS B ON
(
A.[CUSTOMER_ID] = B.[CUSTOMER_ID]
AND A.[GROUP_ID] = @GROUP_ID--起作用了,ON后面的条件相当于做个INNER JOIN+ON中的条件。此时能匹配上的只有group_id:1,customer_id:11
)
WHEN NOT MATCHED THEN --@member_table中有而group_member表中没有的记录,会插入到group_member表,即@group_id:1,customer_id:12
INSERT
(
[CUSTOMER_ID] ,
[GROUP_ID]
)
VALUES
(
B.[CUSTOMER_ID] ,
@GROUP_ID
)
WHEN NOT MATCHED BY SOURCE--group_member表中有而@member_table表中没有的记录,会直接删除,即group_id:1,customer_id:10和group_id:2,customer_id:999
THEN DELETE;
--result:所以结果就是:group_member表插入了1条记录,删除了2条记录; @member_table表的记录不会变
SELECT * FROM [GROUP_MEMBER]
SELECT * FROM @MEMBER_TABLE