面举一个例子来具体说明一下:
有两个表SourceTable为登陆表,TargetTable为授权表,如果访问用户在登陆表中,更新授权表的授权级别,否则授权0表示游客。sql语句如下: --SourceTable为登陆表,TargetTable为授权表
--如果访问用户在登陆表中,更新授权表的授权级别,否则授权0表示游客。
create table SourceTable(UserName nvarchar(10),Pwd int,[Level] int)
create table TargetTable(UserName nvarchar(10),[Level] int)
go
--下面是sql Server2008新增的赋值功能,更多新功能请参见 insert into SourceTable values('user1','111',1),('user2','222',2),('user3','333',3)
insert into TargetTable values('user1',2) 一般情况,我们会写如下的语句:
代码如下:
declare @UserName varchar(10) = 'user2'--表示某个登陆的用户名
merge into TargetTable as tg
using (select UserName,[Level] from SourceTable where UserName=@UserName)
as sr(UserName,[Level]) on tg.UserName=sr.UserName
when matched then
update set [Level]=sr.[Level]--更新授权级别
when not matched by target then
insert (UserName,[Level]) values(@UserName,0)--表示游客
output $action;
执行结果为UPDATE,表示执行了更新操作,也正是我们想要的。 merge into TargetTable as tg
using (select UserName,[Level] from SourceTable where UserName=@UserName)
as sr(UserName,[Level]) on tg.UserName=sr.UserName
when matched then
update set [Level]=sr.[Level]--更新授权级别
when not matched by target then
insert (UserName,[Level]) values(@UserName,0)--表示游客
output $action;
但是如果我们把@UserName赋值为'user6',希望能在TargetTable中插入一条记录,但是实际执行结果为空,显示什么都没执行。原因就是using (select UserName,[Level] from SourceTable where UserName=@UserName) as sr(UserName,[Level]) on tg.UserName=sr.UserName这个语句中,sr结果集为空,所以merge语句就不向后执行了,不知道这是不是sql Server的bug。 下面的sql可以解决上面的问题:
代码如下:
declare @UserName varchar(10) = 'user7'--表示某个登陆的用户名
merge into TargetTable as tg
using (select @UserName)
as sr(UserName) on tg.UserName=sr.UserName
when matched then
update set [Level]= (select top 1 [Level] from SourceTable where UserName=@UserName)
--更新授权级别
when not matched by target then
insert (UserName,0)--表示游客
output $action;
merge into TargetTable as tg
using (select @UserName)
as sr(UserName) on tg.UserName=sr.UserName
when matched then
update set [Level]= (select top 1 [Level] from SourceTable where UserName=@UserName)
--更新授权级别
when not matched by target then
insert (UserName,0)--表示游客
output $action;