• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

为SQL Server数据库传数组参数的变通办_sqlserver

sqlserver 搞代码 3年前 (2018-06-17) 100次浏览 已收录 0个评论

然后在存储过程中用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 [email protected]

Set @PointerCurr=CharIndex(‘,’,@ProductId_Array,@PointerPrev+1)

set @TId=cast(SUBSTRING(@ProductId_Array,@PointerPrev,@[email protected]) as 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,@[email protected]) as 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)[email protected]) as 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

网友Bizlogic对此的改进方法:

应该用SQL2000 Openxml更简单,效率更高,代码更可读:

CREATE Procedure [dbo].[ProductListUpdateSpecialList]

(

@ProductId_Array NVARCHAR(2000),

@ModuleId INT

)

AS

delete from ProductListSpecial where [email protected]

— If empty, return

IF (@ProductId_Array IS NULL OR LEN(LTRIM(RTRIM(@ProductId_Array))) = 0)

RETURN

DECLARE @idoc int

EXEC sp_xml_preparedocument @idoc OUTPUT, @ProductId_Array

Insert into ProductListSpecial (ModuleId,ProductId)

Select

@ModuleId,C.[ProductId]

FROM

OPENXML(@idoc, ‘/Products/Product’, 3)

with (ProductId int ) as C

where

C.[ProductId] is not null

EXEC sp_xml_removedocument @idoc

欢迎大家阅读《为SQL Server数据库传数组参数的变通办_sqlserver,跪求各位点评,若觉得好的话请收藏本文,by 搞代码


喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址