2016-03-30 24 views
1

Ich möchte meine gespeicherten Prozedur, so etwas haben:Verkettungs innerhalb gespeicherte Prozedur

InvoiceNumber = EventCode + EventInstance + EventCount 

Ich bin nicht ganz sicher, wie dies in meinem Setup zu codieren (siehe unten). Ich habe viele Ideen ausprobiert, aber kein Glück.

ALTER PROCEDURE [dbo].[spInvoiceNumber] 
    @EventCode nvarchar(10), 
    @EventInstance nvarchar(10) 
AS 
BEGIN 
    SET NOCOUNT ON; 

    INSERT INTO Payment (EventCode, EventInstance, EventCount) 
    OUTPUT INSERTED.EventCode, INSERTED.EventInstance, INSERTED.EventCount 
     SELECT 
      @EventCode, @EventInstance, ISNULL(MAX(EventCount), -1) + 1 
     FROM 
      Payment 
     WHERE 
      (EventCode = @EventCode AND 
      EventInstance = @EventInstance) 
END 
+0

einen Ausgabeparameter Erstellen Sie für Ihre gespeicherte Prozedur – cha

+0

@cha Können Sie ein Beispiel nennen? – RockOn

+0

Meinen Sie nur eine weitere Zeile zu Ihrem OUTPUT hinzufügen? z.B. 'INSERTED.EventCode + INSERTED.EventInstance + INSERTED.EventCount InvoiceNumber'? – ZLK

Antwort

1
INSERT INTO Payment (EventCode, EventInstance, EventCount, InvoiceNumber) 
    OUTPUT INSERTED.EventCode, INSERTED.EventInstance, 
      INSERTED.EventCount, INSERTED.InvoiceNumber 
    SELECT @EventCode, @EventInstance, 
      isnull(max(EventCount),-1) + 1, 
      EventCode + EventInstance + CONVERT(VARCHAR(10), isnull(max(EventCount),-1) + 1) 
    FROM Payment 
    WHERE (EventCode = @EventCode AND 
     EventInstance = @EventInstance) 
+0

Danke, das hat funktioniert. – RockOn

1

Sie können so etwas wie dies versuchen:

ALTER PROCEDURE [dbo].[spInvoiceNumber] 
     @EventCode nvarchar(10), 
     @EventInstance nvarchar(10) 
AS 

BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 

    DECLARE @InvoiceNumber nvarchar(30) 

    declare @EventCount INT = 
    (select isnull(max(EventCount),-1) + 1 
     FROM Payment 
     WHERE (EventCode = @EventCode AND 
     EventInstance = @EventInstance) 
    ) 

    SELECT @InvoiceNumber = @EventCode + @EventInstance + convert(nvarchar(10),@EventCount) 

    INSERT INTO Payment (EventCode, EventInstance, EventCount, InvoiceNumber) 
    SELECT @EventCode, @EventInstance, @EventCount, @InvoiceNumber 

END