create procedure [dbo].[BcImportVendors]
@items BcVendorImportItems readonly
as
begin
set nocount on
declare @now datetimeoffset = sysdatetimeoffset()
declare @AccountingVendorIdHolder table
(
AccountingVendorFid int not null,
BcId uniqueidentifier not null,
LastUpdatedInBcOn datetimeoffset not null
)
;with MergeData as
(
select
BcVendor.AccountingVendorFid,
Items.BcId,
Items.[Name],
Items.Number,
Items.Phone,
Items.Ten99Type,
Items.LastModified
from @items Items
left outer join BcVendor on Items.BcId = BcVendor.BcId
)
merge AccountingVendor with (tablock) using MergeData on
MergeData.AccountingVendorFid = AccountingVendor.AccountingVendorId
when matched then update set
[Name] = MergeData.[Name],
VendorNumber = MergeData.Number,
Phone = MergeData.Phone,
Ten99Type = MergeData.Ten99Type
when not matched then
insert
(
[Name],
VendorNumber,
OnHold,
Phone,
Ten99Type
)
values
(
MergeData.[Name],
MergeData.Number,
0,
MergeData.Phone,
MergeData.Ten99Type
)
output
inserted.AccountingVendorId,
MergeData.BcId,
MergeData.LastModified
into @AccountingVendorIdHolder;
;with MergeData as
(
select
AccountingVendorIdHolder.BcId,
AccountingVendorIdHolder.AccountingVendorFid,
LastUpdatedInBcOn
from @AccountingVendorIdHolder as AccountingVendorIdHolder
)
merge BcVendor with (tablock) using MergeData on
MergeData.BcId = BcVendor.BcId
when matched then update set
LastImportedOn = @now
when not matched then
insert
(
BcId,
AccountingVendorFid,
CreatedOn,
LastImportedOn,
LastUpdatedInBcOn
)
values
(
MergeData.BcId,
MergeData.AccountingVendorFid,
@now,
@now,
LastUpdatedInBcOn
);
end
GO
GRANT EXECUTE ON [dbo].[BcImportVendors] TO [MssExec]
GO