如何从“使用输出子句更新”查询中返回不同的结果

时间:2018-07-16 06:18:48

标签: sql-server tsql sql-server-2012

UPDATE top (5) Alert SET Notify = 1 OUTPUT inserted.OrderNo as orderNo,inserted.UserId as userId 
  where UserId = ('rekon') and Notify = 0

这是我的带有输出子句的更新查询,记录会针对具有匹配userId的所有条目进行更新,但是由于输出子句,有没有办法我只能限制不同的OrderNo?

UserId  OrderNo     Notify  ProcessedTime
rekon   3006856996     0             25:08.7
rekon   3006856996     0             12:05.9
rekon   3006856996     0             18:56.9
rekon   3006857268     0             12:27.0
rekon   3006857015     0             20:59.9
rekon   3006857015     0             14:08.8
rekon   3006856996     0             47:16.0
rekon   3006857015     0             27:11.3
rekon   3006857015     0             49:20.7

1 个答案:

答案 0 :(得分:0)

OUTPUT子句的定义类似于this

  

:: = {
      [输出到{@table_variable | output_table} [(column_list)]]
      [输出]} :: = {| scalar_expression} [[AS] column_alias_identifier]
      [,... n]

     

:: = {已删除|插入from_table_name}。 {* |   column_name}
      | $ action

因此您可以像这样使用它:

UPDATE TOP (5) Alert 
   SET Notify = 1 
OUTPUT inserted.OrderNo as orderNo,
       inserted.UserId as userId
 INTO #tmpNotify
WHERE UserId = ('rekon') 
  AND Notify = 0

-- then select it:
SELECT distinct orderNo,
                 userId
  FROM #tmpNotify