给SQL Server存储过程,传送数组参数的变通办法

 最近一直在做Dnn模块的开发,过程中碰到这么一个问题,需要同时插入N条数据,不想在程序里控制,但是SQL Sever又不支持数组参数.所以只能用变通的办法了.利用SQL Server强大的字符串处理传把数组格式化为类似"1,2,3,4,5,6"
 然后在存储过程中用SubString配合CharIndex把分割开来

详细的存储过程

CREATE PROCEDURE dbo.ProductListUpdateSpecialList
    
@ProductId_Array varChar(800),
    
@ModuleId int
AS
    
DECLARE @PointerPrev int
    
DECLARE @PointerCurr int
    
DECLARE @TId int
    
Set @PointerPrev=1
    
set @PointerCurr=1
    
    
begin transaction
    
Set NoCount ON
    
delete  from ProductListSpecial where ModuleId=@ModuleId
    
    
Set @PointerCurr=CharIndex(',',@ProductId_Array,@PointerPrev+1)
    
set @TId=cast(SUBSTRING(@ProductId_Array,@PointerPrev,@PointerCurr-@PointerPrevas int)
    
Insert into ProductListSpecial (ModuleId,ProductId) Values(@ModuleId,@TId)
    
SET @PointerPrev = @PointerCurr
    
while (@PointerPrev+1 < LEN(@ProductId_Array))
    
Begin
        
Set @PointerCurr=CharIndex(',',@ProductId_Array,@PointerPrev+1)
        
if(@PointerCurr>0)
        
Begin
            
set @TId=cast(SUBSTRING(@ProductId_Array,@PointerPrev+1,@PointerCurr-@PointerPrev-1as int)
            
Insert into ProductListSpecial (ModuleId,ProductId) Values(@ModuleId,@TId)
            
SET @PointerPrev = @PointerCurr
        
End
        
else
            
Break
    
End
    
    
set @TId=cast(SUBSTRING(@ProductId_Array,@PointerPrev+1,LEN(@ProductId_Array)-@PointerPrevas int)
    
Insert into ProductListSpecial (ModuleId,ProductId) Values(@ModuleId,@TId)
    
Set NoCount OFF
    
if @@error=0
    
begin
        
commit transaction
    
end
    
else
    
begin
        
rollback transaction
    
end
GO
posted @   无心之柳.NET  阅读(7449)  评论(12编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示