在merge语句中为变量设置一个值

时间:2013-10-21 11:08:49

标签: sql sql-server-2008 tsql

感谢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变量中,如上所述。

非常感谢任何帮助。 中号

1 个答案:

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