有条件地将列添加到存储过程

时间:2015-10-02 09:06:19

标签: sql-server stored-procedures

我有以下(简化)存储过程:

:empty

我的问题是,当FulfilmentID = 4时,我想添加一个额外的字段 - '交付'

如果尝试过以下操作:

    CREATE FUNCTION [dbo].[UDF_FulfilmentBatch](@FulfilmentID INT) RETURNS
    @Result TABLE (
            [sequence]  INT,
            membershipid    BIGINT,
            membershipNo    VARCHAR(255)
    )
    AS
    BEGIN

    DECLARE @_sequence  INT
    DECLARE @_membershipid  BIGINT
    DECLARE @_membershipNo  VARCHAR(255)

    SET @_sequence = 1

    IF @FulfilmentID = 4
    BEGIN
        DECLARE FulfilCursor CURSOR FAST_FORWARD FOR 
            SELECT * from VW_FulfilmentExtract_HH
    END
IF @FulfilmentID = 3
    BEGIN
        DECLARE FulfilCursor CURSOR FAST_FORWARD FOR 
            SELECT * from VW_FulfilmentExtract_ID
    END
    ELSE IF @FulfilmentID = 2
    BEGIN
        DECLARE FulfilCursor CURSOR FAST_FORWARD FOR 
            SELECT * from VW_FulfilmentExtract_Art
    END
    ELSE
        DECLARE FulfilCursor CURSOR FAST_FORWARD FOR 
            SELECT * from VW_FulfilmentExtract_Tha

    OPEN FulfilCursor

    FETCH NEXT FROM FulfilCursor INTO @_membershipid, @_membershipNo

    WHILE @@FETCH_STATUS = 0 BEGIN

        INSERT INTO @Result
        VALUES (@_sequence, @_membershipid, @_membershipNo) 

        SET @_sequence = @_sequence + 1 

        FETCH NEXT FROM FulfilCursor INTO @_membershipid, @_membershipNo
    END

    CLOSE FulfilCursor
    DEALLOCATE FulfilCursor

    RETURN

    END




    GO

但这不起作用(请原谅任何语法错误,这是SO的粗略输入)

搜索网页的形式似乎没有多少。可以吗?

1 个答案:

答案 0 :(得分:2)

您的代码中存在许多问题:

  • 使用SELECT *
  • 使用光标
  • ...

最后,它过于复杂,看起来很像应用程序代码(C#,java,...)

您想要做的事情应该是使用一个Select(即在一组数据上)。列名也应列在SELECT和FROM之间。

一个选项是:

CREATE FUNCTION [dbo].[UDF_FulfilmentBatch](@FulfilmentID INT) RETURNS TABLE
AS
RETURN (
    SELECT sequence = ROW_NUMBER() Over(Order By (Select 1))
        , _membershipid, membershipNo, delivery
    FROM VW_FulfilmentExtract_HH
    WHERE @FulfilmentID = 4

    UNION ALL

    SELECT sequence = ROW_NUMBER() Over(Order By (Select 1))
        , _membershipid, membershipNo, delivery = NULL
    FROM VW_FulfilmentExtract_ID
    WHERE @FulfilmentID = 3

    UNION ALL

    SELECT sequence = ROW_NUMBER() Over(Order By (Select 1))
        , _membershipid, membershipNo, delivery = NULL
    FROM VW_FulfilmentExtract_Art
    WHERE @FulfilmentID = 2

    UNION ALL

    SELECT sequence = ROW_NUMBER() Over(Order By (Select 1))
        , _membershipid, membershipNo, delivery = NULL
    FROM VW_FulfilmentExtract_Tha
    WHERE @FulfilmentID = not in (2, 3, 4)
);

这里我使用ROW_NUMBER生成您的序列号。

我添加了Delivery列,并在不需要时将其设置为NULL。

您必须更新列名称。我猜他们。

顺便说一下,这不是存储过程,而是Inline User-Defined Functions