SQL Server - 存储过程返回案例结果表达式

时间:2014-08-30 15:21:59

标签: sql sql-server stored-procedures case procedure

我想使用CASE语句中的过程返回。它不能是一个函数,因为该过程返回一个插入的键。

    UPDATE TIM 
    SET CD_LINHA_EVENTO = 
        CASE WHEN 
            TIM.CD_SUBESTRUTURA_PARAMETRO = (SELECT TOP 1 SPZ.CD_SUBESTRUTURA_PARAMETRO FROM SUBESTRUTURA_PARAMETRO SPZ WITH (NOLOCK) WHERE SPZ.CD_SUBESTRUTURA = TIM.CD_SUBESTRUTURA 
                                                AND SPZ.FL_SELECAO = 1 ORDER BY SPZ.NR_ORDEM)
            THEN 
                **EXEC [dbo].[SPRTO_NumeracaoEventos]**
            ELSE 
            (SELECT MAX(TIM2.CD_LINHA_EVENTO) FROM #TB_INSERTED_MODIFIED TIM2 WITH(NOLOCK))
            END
    FROM #TB_INSERTED_MODIFIED TIM WITH (NOLOCK)    

存储过程[SPRTO_NumeracaoEventos]:

INSERT INTO TB_NUMERACAO_EVENTOS (VALOR) VALUES ('')
RETURN SCOPE_IDENTITY()

谢谢!

1 个答案:

答案 0 :(得分:0)

我无法很好地找出你的表模式以提供直接的答案,但我总结了一种在更新触发器中使用插入的标识值的方法。希望您能够根据具体用例进行调整。

看看这个SQL Fiddle

如小提琴中的注释所述,此策略基于使用OUTPUT子句将标识值捕获到表变量中。有关OUTPUT子句的更多信息,请参阅http://msdn.microsoft.com/en-us/library/ms177564.aspx

对于大小写为true的行,我们将每个真实案例中的一行插入到辅助表中并将标识捕获到表变量中,然后使用插入的虚拟表和标识之间的行号连接更新基础表表变量。然后我们为case为false的行运行另一个更新。这是我小提琴示例中的相关触发器代码。

-- Create a table variable to hold identity ID values from OUTPUT clause
DECLARE @table_2_ids TABLE (id INT NOT NULL)

-- Insert to our secondary table where the condition is true and capture the identity values to table variable
INSERT table_2 (textval) 
OUTPUT inserted.id INTO @table_2_ids 
SELECT 'from trigger'
FROM inserted
WHERE flag = 1

-- Use row number to match up rows from inserted where the condition is true to the identity value table variable
-- Update matched identity id to underlying table
UPDATE t
SET table_2_id = r.id, textval = textval + ' and trigger inserted to table_2'
FROM table_1 t
JOIN (SELECT id, ROW_NUMBER() OVER (ORDER BY id) rn FROM inserted WHERE flag = 1) i ON i.id = t.id
JOIN (SELECT id, ROW_NUMBER() OVER (ORDER BY id) rn FROM @table_2_ids) r ON r.rn = i.rn

-- and now update where condition is false
UPDATE t
SET textval = textval + ' and trigger did not insert to table_2'
FROM table_1 t
WHERE flag = 0