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)

查询 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)

查询 1 工作正常。在 query2 中,我将替换为 de 定义的变量,在该变量中我传递给函数 fnSplit,在该函数中我用逗号分隔值。我收到一条错误消息Must declare the scalar variable "@OfferID"。请让我知道这里的问题在哪里。

4

1 回答 1

2

您必须从外部输入值并将 ' 替换为 ":

查询 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)

另一种解决方案(也是更好的解决方案)是使用sp_executesql


请注意,动态 SQL 是一种进行 sql 注入的方法,您应该避免使用它。

于 2012-05-02T09:01:55.047 回答