I am writing a procedure to produce an int output variable, but I'm not sure how to do this using dynamic sql. If I execute the below procedure I get the @AnlyNum value displayed in the results screen, but I just want @AnlyNum variable set with a value so I can use it. Thank you.
Create procedure [dbo].[sp_test] @Db varchar(50), @RwNum int, @AnlyNum int output
As
Begin
Declare @Sql nvarchar(max) =
'Select ''@AnlyNum'' = (Select AnlyId From '+@Db+'..Test order by AnlyId desc OFFSET '+convert(varchar(10),@RwNum)+' rows fetch next 1 rows only)'
End
exec(@Sql)
EXEC (@SQL);. Such statements cannot be parametrised, which promote bad habits that result in security flaws like SQL injection. If you need to run a statement that is within a variable or literal string then usesys.sp_executesql. Then you can easily parametrise the statement if you need to (and in this case, easily consume theOUTPUTparameter from the dynamic statement).EXEC (@SQL)syntax). Never inject unsanitised values into a dynamic statement. Properly quote dynamic objects withQUOTENAMEand properly parametrise parameters.sp_is reserved, by Microsoft, for Special / System Procedures. It should not be used for User Procedures. Doing so comes with a performance cost and the risk of your Procedure simply not working one day after an update/upgrade. Either use a different prefix or (possibly better) no prefix at all. Is the sp_ prefix still a no-no?