存储过程中的连接

时间:2016-03-30 04:26:32

标签: sql sql-server stored-procedures

我希望在我的存储过程中有类似的东西:

InvoiceNumber =  EventCode + EventInstance + EventCount

我不太确定如何将其编码到我的设置中(见下文)。我尝试过很多想法,但没有运气。

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

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

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

答案 1 :(得分: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)