Jayraj Chhaya

Jayraj Chhaya

  • 335
  • 4.8k
  • 66.7k

SQL Data Clone Using Merge statement

Jan 16 2024 11:08 AM

Hi Folks,

When the data is a match then I want to call SP and Insert the record in a different table.

How can I set and check conditionally like the case when or If else with a different table Insert or Update?

Look at the below code for a better understanding

 

DECLARE @SqlQuery VARCHAR(MAX)
SET @SqlQuery = 
		   'MERGE ' + QUOTENAME(@MainDB) + '.[dbo].[tblTax_M] AS T  
			USING (SELECT * FROM ' + QUOTENAME(@DbName) + '.[dbo].[tblTax_M] ) AS S 
				ON T.TAXNAME = S.TAXNAME 	
			WHEN MATCHED THEN 
				IF (S.Type = 1)
				BEGIN
					SET @Type = 0
				END
				EXEC SP_InsertTye S.Type
				Update T.Type = @Type *12 
				 
			WHEN NOT MATCHED BY TARGET THEN 
				INSERT  
					([TaxId],[BranchId],[TAXNAME],[PERCENTAGE],[Type],[CreatedDate],[Amount],[CreatedBy],[IsDeleted],[TaxType],[IsIncludedInPrice]
					,[indicator],[isPromptExemption],[pctStartAmt],[Sysid])
				VALUES
					(S.TaxId,S.BranchId,S.TAXNAME,S.PERCENTAGE,S.Type,S.CreatedDate,S.Amount,S.CreatedBy,S.IsDeleted,S.TaxType,S.IsIncludedInPrice
					,S.indicator,S.isPromptExemption,S.pctStartAmt,S.Sysid);'
		   			
	PRINT 'Tax(tblTax_M) data insert successfully'
	EXEC sp_executesql @SqlQuery

 


Answers (2)