1

Query 1:

  SET @sql2 = 'insert into TempReport   
  select ID, max(TransactionTime),0 from  ClubTransaction with (nolock)  
  where ClubcardID in (select ClubcardID from TempCC)   
  and ClubcardTransaction.OfferID  not in (119,120,121)  
  group by ClubcardID' 
  exec (@Sql2)

Query 2:

  delcare @OfferID varchar(50)
  set   OfferID='1,112,445,'  
  SET @sql2 = 'insert into TempReport   
  select ID, max(TransactionTime),0 from  ClubTransaction with (nolock)  
  where ClubcardID in (select ClubcardID from TempCC)   
  and ClubcardTransaction.OfferID not in (Select Item From dbo.fnSplit(@OfferID,'','')   
  group by ClubcardID'    
  exec (@Sql2)

Query 1 works fine. In query2 I am replacing with an variable de defined where I am passing to the function fnSplit where I split the values with comma separated. I get an error message Must declare the scalar variable "@OfferID". Please let me know where is the issue here.

0

1 Answer 1

2

You have to put the value from outside and replace the ' by ":

Query 2:

  declare @OfferID varchar(50)
  set   OfferID='1,112,445,'  
  SET @sql2 = 'insert into TempReport   
  select ID, max(TransactionTime),0 from  ClubTransaction with (nolock)  
  where ClubcardID in (select ClubcardID from TempCC)   
  and ClubcardTransaction.OfferID not in (Select Item From dbo.fnSplit(' + replace(convert(varchar(4000), @OfferID), '''', '''''') + ',"","")   
  group by ClubcardID'    

  exec (@Sql2)

Another solution (and a better one) is to use sp_executesql


Be aware that dynamic SQL is a way to make sql injections and you should avoid using it..

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.