Search code examples
stored-proceduressql-server-2008-r2while-loopsql-updatesp-executesql

Need help to debug T-SQL stored procedure that has sql scripts stored in a table


In this stored procedure, I read from a third party vendor table named M_SopInsert.

SQLScript is the column name and every record in this table contains a SQL query that does an UPDATE, INSERT or DELETE.

I can see the actual script when I debug it using Select (commented below). But the script itself doesn't execute and I don't see any errors.

I tried hardcoding an UPDATE statement below and it works fine.

What could be the issue here?

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
declare @sopScript nvarchar(1000)

select SQLScript into #ControlTbl from  M_SopInsert 
where soptype = @I_vSOPTYPE and sopnumbe = @I_vSOPNUMBE and lnitmseq = @I_vLNITMSEQ

while exists (select * from #ControlTbl)
begin

   select top 1 @sopScript = SQLScript
   from #ControlTbl

   --exec executesql @sopScript = SQLScript 
   --select @sopScript
   --EXEC sp_executesql @sopScript;
   --EXEC sp_executesql "update SOPQty set QTYORDER = '17.89' where LNIT = '16'"
exec sp_executesql @sopScript = SQLScript
   delete from #ControlTbl where SQLScript = @sopScript

end
drop table #ControlTbl
return (@O_iErrorState)

Solution

  • I replaced "exec sp_executesql @sopScript = SQLScript" with "exec sp_executesql @sopScript" and it worked.. I don't know what difference it would make.