首页 > 代码库 > 存储过程中动态执行SQL并获取返回结果

存储过程中动态执行SQL并获取返回结果

很久没有写存储过程了,因为存储过程违背OOP精神,话说带了参数的存储过程,如果业务需求改变,改存储过程还真的挺麻烦的。所以现在比较倾向于负责的业务逻辑在业务层去处理,业务层专门做业务层的事情。

 

通过一层巧妙地包装,动态执行SQL语句就解决了

ALTER procedure [dbo].[PROC_NextSteps](@Count int,@IDS NVARCHAR(500),@Rules NVARCHAR(MAX),@IDSOut NVARCHAR(500) OUT)asBEGINset @Rules=UPPER(@Rules);set @IDSOut=‘‘declare @index intset @index=1;WHILE(@index<=@Count)BEGINDECLARE @SplitRule NVARCHAR(MAX),@Value intselect @SplitRule=dbo.F_SplitOfIndex(@Rules,|,@index)if(CHARINDEX(SELECT,@SplitRule)=1)begindeclare @sql nvarchar(1000)select @sql=Nselect @Value=http://www.mamicode.com/(+@SplitRule+) exec sp_executesql  @sql, N@Value int out,@Value outendELSE IF(CHARINDEX(PROC_,@SplitRule)=1)BEGINexec @Value =  @SplitRuleENDELSEBEGINset  @Value =http://www.mamicode.com/  @SplitRuleENDif(@Value>=1)beginselect @IDSOut=@IDSOut+dbo.F_SplitOfIndex(@IDS,|,@index)+|endset @index=@index+1endif(@IDSOut<>‘‘)beginset @IDSOut=LEFT(@IDSOut,LEN(@IDSOut)-1)endEND

declare @res nvarchar(1000)
EXEC [dbo].[proc_nextsteps] 3,‘id1|id2|id3‘,‘SELECT COUNT(1) FROM dbo.A_CDKey|PROC_B|0‘,@res OUT
print @res

 

存储过程中动态执行SQL并获取返回结果