数据库

 首页 > 数据库 > SqlServer > 为SQL Server数据库传数组参数的变通办法

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

分享到:
【字体:
导读:
         摘要: 最近一直在做Dnn模块的开发,过程中碰到这么一个问题,需要同时插入N条数据,不想在程序里控制,但是SQL Sever又不支持数组参数.所以只能用变通的办法了.利用SQL Server强大的字符串处理传...

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

 

为SQL Server数据库传数组参数的变通办法
分享到:
当数据库出现页损坏或校验和出错时如何处...
当数据库出现页损坏或校验和出错时如何处理   当数据库出现页损坏或校验和出错时如何处理   作者:nzperfect / perfectaction   日期:2009.09.27   Email:nzperfect@gmail.com   最近一直在进一步学习数据库故障的处理方面的知识,做为一个数据库维护人员,我即期望遇到所有的数据库出错的案例,以增加自己的经...
优化SQL语句需要注意的4点
优化SQL语句需要注意的4点   1.尽量不要对列名进行函数处理。而是针对后面的值进行处理   例如where col1 = -5的效率比where -col1=5的效率要高   因为后面的条件对列值进行了计算。这样的条件下优化器无法使用索引   而是要针对所有值进行计算之后才能再比较   2.尽量使用和数剧列一样的值进行操作   如果col1...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……