合并后选择查询不起作用

时间:2013-01-16 20:08:50

标签: sql sql-server sql-server-2008 merge

我正在执行以下步骤:

  • 合并stmt。如果不存在,合并语句会将值插入到视图中。
  • 选择stmt。选择我插入的记录

但是select查询返回空白。示例代码如下:

declare @now AS DATETIME = GETUTCDATE(),
        @uuid AS INT = 1;

MERGE A.V_Table AS T
(
  Select 
     A1,
     A2
  FROM B.Table
)S
on T.A1 = T1.A1
   and T.A2 = T1.A2
when not matched by target then
insert
(
  A1,
  A2,
  UpdateUUID,
  UpdateTimeStamp
)
values
(
 s.a1,
 s.a2,
 @uuid,
@now
);

select *
from A.V_Table
where updateuUid = @uuid and UpdateTimeStamp = @now;

如果我打印出@now和@uuid的值并在select查询中使用这些值,则返回记录。但不是当它按上述方式执行时。

知道为什么会这样吗?选择查询是否仅在合并完成后运行?

1 个答案:

答案 0 :(得分:0)

在合并过程之后,您所缺少的是“GO”关键字:

declare @now AS DATETIME = GETUTCDATE(),
        @uuid AS INT = 1;

MERGE A.V_Table AS T
(
  Select 
     A1,
     A2
  FROM B.Table
)S
on T.A1 = T1.A1
   and T.A2 = T1.A2
when not matched by target then
insert
(
  A1,
  A2,
  UpdateUUID,
  UpdateTimeStamp
)
values
(
 s.a1,
 s.a2,
 @uuid,
@now
); 
GO

select *
from A.V_Table
where updateuUid = @uuid and UpdateTimeStamp = @now;