為SQL Server資料庫傳陣列引數的變通辦法

iSQlServer發表於2009-10-23

最近一直在做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-@PointerPrev) 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,@PointerCurr-@PointerPrev-1) 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)-@PointerPrev) 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 ModuleId=@ModuleId

-- 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

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/16436858/viewspace-617306/,如需轉載,請註明出處,否則將追究法律責任。

相關文章