0

感谢 NLwino 提出这个问题: Using output to set a variable in a merge statement

我正在寻找从 MERGE 内部返回我的新 counter_ 的值:

        DECLARE @CounterType VARCHAR(50)
        SET @CounterType = 'Case';

        MERGE [dbo].[AN_Counter] WITH(ROWLOCK) TARGET

        USING(SELECT @CounterType) SOURCE([KEY])
        ON TARGET.[System_Name] = SOURCE.[KEY]

        WHEN MATCHED THEN

              UPDATE
                 SET COUNTER_ = COALESCE(COUNTER_,0) + 1

              SELECT @CounterType = COALESCE(Prefix,'') + CAST(SUBSTRING('0000000000000000000000000000',1,padding - LEN(CAST (Counter_ AS VARCHAR ))) + CAST (Counter_ AS VARCHAR ) AS VARCHAR)

        ;

我想执行合并,并将新值放入 @CounterType 变量中,如上所述。

任何帮助深表感谢。米

4

1 回答 1

0

我设法完成了它,我想在这里分享我是如何做到的:

SELECT * FROM  [dbo].[AN_Counter]   WHERE System_Name = 'Case'   

DECLARE @CounterType VARCHAR(50)
SET @CounterType = 'Case'  

DECLARE @RADHE TABLE (
[Counter_] [int] NULL,
[Prefix] [varchar](10) NULL,
[Padding] [int] NULL
)

BEGIN TRANSACTION TR_ORDER_NUMBERS


INSERT INTO @RADHE( 
                 [Counter_]
                ,[Prefix]
                ,[Padding]
               )

SELECT  
                 [Counter_]
                ,[Prefix]
                ,[Padding]
FROM                  
(
        MERGE [dbo].[AN_Counter] WITH(ROWLOCK) TARGET

        USING(SELECT @CounterType) SOURCE([KEY])
        ON TARGET.[System_Name] = SOURCE.[KEY]

        WHEN MATCHED THEN

              UPDATE
                 SET COUNTER_ = COALESCE(COUNTER_,0) + 1

        OUTPUT $Action AS The_Action
               ,INSERTED.Counter_ 
               ,INSERTED.Prefix   
               ,INSERTED.Padding  
) Outputs
WHERE The_Action = 'UPDATE';

SELECT * FROM  [dbo].[AN_Counter] 
     WHERE System_Name = 'Case' 

SELECT * FROM @RADHE

SELECT COALESCE(R.Prefix,'') + CAST(SUBSTRING('0000000000000000000000000000',1,R.Padding - LEN(CAST (R.Counter_ AS VARCHAR ))) + CAST (R.Counter_ AS VARCHAR ) AS VARCHAR)
FROM @RADHE R


SELECT XACT_STATE()  
于 2013-10-21T14:23:13.777 回答