Home > OS >  if else change declared variable in database SQL
if else change declared variable in database SQL

Time:10-24

I don't know how to change the value of already declared variable. I want to update something in my table base on the declared variable.

what I've tried so far

  IF NOT EXISTS                                   
  (SELECT  1 FROM [DB_databaseOne].[dbo].[data_tblOne]                                      
    WHERE orderBy= 'AC038234'             
    and prodCode = 'P0008'            
    and batchID = '1'                        
    and is_buy = 3 and voidFlag is null)
     BEGIN
          DECLARE @MSG VARCHAR(300) = 'GOOD'
     END
  ELSE
     BEGIN 
          DECLARE @MSG VARCHAR(300) = 'NOT GOOD'
     END

CodePudding user response:

You should DECLARE your variable only once. You can have multiple SET statements to assign a value:

DECLARE @MSG VARCHAR(300)   

IF NOT EXISTS                                   
  (SELECT  1 FROM [DB_databaseOne].[dbo].[data_tblOne]                                      
    WHERE orderBy= 'AC038234'             
    and prodCode = 'P0008'            
    and batchID = '1'                        
    and is_buy = 3 and voidFlag is null)
     BEGIN
          SET @MSG =  'GOOD'
          PRINT @MSG
     END
  ELSE
     BEGIN 
          SET @MSG = 'NOT GOOD'
          PRINT @MSG
     END
  • Related