I have a query that updates a table using a table valued parameter so that I can update a number a rows at the same time based on the table valued parameter. I also need to generate a number for every row updated and put it into the invoice column of the table. This number has to be taken from the AR table to find the max invoice number and add 1 to it for the first row and for each subsequent row it should add another row. How can I do that within the join?
USE [Trial]GO
/****** Object: StoredProcedure [dbo].[SaveAsInvoice_Update] Script Date: 03/19/2014 11:37:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:Debra
-- Create date: December 25, 2013
-- Description:Update work orders to invoices
-- =============================================
ALTER PROCEDURE [dbo].[SaveAsInvoice_Update]
-- Add the parameters for the stored procedure here
@SaveAsInvoice AS SaveAsInvoice READONLY
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
--UPDATE ARH SET INVOICE = @Invoice, STATUS = 'inv' WHERE ARHID IN (SELECT ID FROM @ARHIDs)
MERGE INTO ARH target
USING (SELECT ARHID, INVOICE FROM @SaveAsInvoice) AS source
ON target.ARHID = source.ARHID
WHEN MATCHED THEN
UPDATE
SET INVOICE = source.INVOICE, STATUS = 'inv', PRINTED = 0;
UPDATE INV SET ONHAND = ONHAND - NEW.Qty ,STAMPED = CASE WHEN INV.TYPE = 'CIG' THEN STAMPED - NEW.QTY ELSE 0 END,
LASTDATE = CONVERT(DATE, GETDATE())
FROM (SELECT ARD.ITEM, QTY, ARD.ARHID FROM ARD JOIN @SaveAsInvoice s ON (ARD.ARHID = s.ARHID))NEW
JOIN INV ON NEW.ITEM = INV.ITEM
END
Debra has a question