SQL Merge在匹配时返回目标中的所有行

时间:2013-06-25 17:40:46

标签: sql-server sql-server-2008 sql-server-2008-r2 sql-server-2012

我有以下SQL Merge语句。

DECLARE @TmpTable TABLE (BusinessBaseID int, BatchID uniqueidentifier, SupplierID int, SupplierVenueID varchar(200), AddressID int,[Action] varchar(50))

DECLARE @noop int;  -- needed for the NO-OP below
Declare @TestOp Varchar(max)
Set @TestOp = 't'

-- Insert into BusinessBase retrieving all inserted BusinessBaseIDs mappings via tmptable
-- Another SQL blck goes here to insert records into TEMP table

MERGE Business.Address AS t 
USING (SELECT tmp.BusinessBaseID, tmp.BatchID, tmp.SupplierID, tmp.SupplierVenueID,
v.Name, v.AddressLine1, v.AddressLine2, v.City, v.County, v.PostalCode,
v.Latitude, 
v.Longitude, 
dbo.GetVenueId(v.AddressLine1, v.AddressLine2, v.City, v.County, v.PostalCode, 'GB', v.Latitude, v.Longitude) as VenueId
FROM @TmpTable as tmp INNER JOIN Supplier.VenueImport as v
ON tmp.BatchID = v.BatchID AND tmp.SupplierID = v.SupplierID AND tmp.SupplierVenueID = v.SupplierVenueID
WHERE (tmp.BatchID = 'D7F369F1-A66A-4440-8D4B-2F521F672916') AND (tmp.SupplierID = 17)
) AS s
ON S.VenueId >0
 WHEN MATCHED THEN
  UPDATE SET @TestOp = @TestOp + ':' +convert(varchar, S.VenueId)+'|'+Convert(varchar,t.AddressId)  -- the NO-OP instead of update
WHEN NOT MATCHED BY TARGET THEN
  INSERT (AddressLine1, AddressLine2, City, StateProvince,PostalCode,CountryCode,Lat,Long)
  VALUES (AddressLine1, AddressLine2, City, County, PostalCode, 'GB', Latitude, Longitude)
OUTPUT s.BusinessBaseID, s.BatchID, s.SupplierID, s.SupplierVenueID,ISNULL(INSERTED.AddressID,deleted.addressId),$action INTO @TmpTable;

Select @TestOp;
Select @Temp where [Action] = 'Update'

以上查询返回所有行(新插入的记录除外)。因为它假设只返回1条记录,因为S.VenueId只有一条记录大于0。

dbo.GetVenueId is a function which returns an integer. It will be > 0 for existing records and -1 for not existing records.

有人能指出我做错了吗。

谢谢, 纳雷什

0 个答案:

没有答案