0

我有以下 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.

有人可以指出我做错了什么。

谢谢,纳雷什

4

0 回答 0