查询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"
。
请告诉我这里的问题在哪里。
答案 0 :(得分:2)
您必须从外部输入值并替换“by”:
查询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注入的方法,你应该避免使用它..