2013-10-21 58 views
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變量中,如上所述。

任何幫助,非常感謝。 中號

回答

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() 
相關問題