INAD JOIN在UPDATE OUTPUT中的一个t-sql查询中

时间:2010-11-13 01:16:57

标签: sql sql-server tsql

需要INNER JOIN UPDATE OUTPUT返回的结果集与另一个表并返回结果。有可能吗?

这是一个小例子:

CREATE TABLE [dbo].[Customers]
(   
   [CustomerId] [int],   
   [CustomerName]  [nvarchar](50)
)
GO

CREATE TABLE [dbo].[Orders]
(   
   [OrderId] [int],   
   [OrderName]  [nvarchar](50)
)
GO

CREATE TABLE [dbo].[CustomerOrders]
(   
   [CustomerId] [int],   
   [OrderId]  [int]
)
GO

INSERT INTO CustomerOrders (CustomerId, OrderId) VALUES (1, 1)
INSERT INTO CustomerOrders (CustomerId, OrderId) VALUES (1, 2)
INSERT INTO CustomerOrders (CustomerId, OrderId) VALUES (2, 1)
GO

需要在CustomerOrders表上更新OrderId并返回客户名称,一次性全部。到目前为止,我只能返回CustomerIds:

UPDATE CustomerOrders SET OrderId=NULL 
OUTPUT Deleted.CustomerId
WHERE OrderId='1'

1 个答案:

答案 0 :(得分:24)

TSQL / SQL Server 2005+支持UPDATE子句中的JOIN - 请参阅documentation

UPDATE CUSTOMERORDERS
   SET orderid = NULL
OUTPUT c.customername
  FROM CUSTOMERORDERS co
  JOIN CUSTOMERS c ON c.customerid = co.customerid