在我们记录购票的应用程序中,我们决定如果订单上填写的客户信息与已经存在的记录匹配,那么我们不会在我们的客户表中添加新记录。
我使用MERGE(SQL Server 2008)仅在记录不匹配时插入。如果记录匹配(并且未插入)或者插入记录并创建新的CustomerID,我需要尝试输出CustomerID。有没有正确的方法来解决这个问题?
CREATE PROCEDURE [dbo].[uspMergeCustomer]
-- Add the parameters for the stored procedure here
@lastName varchar(40),
@firstName varchar(30),
@email varchar(50),
@emailNote varchar(100) = null,
@address1 nvarchar(200) = null,
@address2 nvarchar(50),
@city nvarchar(50),
@state char(2),
@zip char(10)
AS
BEGIN
SET NOCOUNT ON;
MERGE Customer WITH (HOLDLOCK)
USING (VALUES (@lastName, @firstName, @email, @emailNote, @address1, @address2, @city, @state, @zip))
Source (LastName, FirstName, Email, EmailNote, AddressLine1, AddressLine2, City, State, Zip)
ON (Customer.LastName = Source.LastName
AND Customer.FirstName = Source.FirstName
AND Customer.Email = Source.Email
AND Customer.AddressLine1 = Source. AddressLine1
AND Customer.City = Source.City
AND Customer.State = Source.State
AND Customer.Zip = Source.Zip)
WHEN NOT MATCHED THEN
INSERT (LastName, FirstName, Email, EmailNote, AddressLine1, AddressLine2, City, State, Zip)
VALUES (@lastName, @firstName, @email, @emailNote, @address1, @address2, @city, @state, @zip)
OUTPUT INSERTED.CustomerID AS NEWID;
END