用户名: 密码: 验证码:           网站地图 高级搜索 RSS订阅 收藏本站
Google
您的位置:首页>>网络编程>>MSSQL>>阅读资讯:怎样同时插入N条数据而不在程序里控制

怎样同时插入N条数据而不在程序里控制

[ 来源: | 阅读:次 | 更新日期:2007-9-7 23:39:04 | 评论 0 条 | 我要投稿 ]

问:“怎样同时插入N条数据,却不在程序里控制?”

www.yueluo.net

答:“由于SQL Sever不支持数组参数.所以只能用另类的办法了.利用SQL Server强大的字符串处理传把数组格式化为类似"1,2,3,4,5,6"。

www.yueluo.net

然后在存储过程中用SubString配合CharIndex把分割开来。

字串6

详细的存储过程: www.yueluo.net

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 yueluo.net

改进方法:

月落

应该用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 月落


Tags:怎样同时插入N条数据而不在程序里控制
责任编辑:
您的评论
用户名:新注册) 密码: 匿名评论 [所有评论]

·用户发表意见仅代表其个人意见,并且承担一切因发表内容引起的纠纷和责任
·本站管理人员有权在不通知用户的情况下删除不符合规定的评论信息或留做证据
·请客观的评价您所看到的资讯,提倡就事论事,杜绝漫骂和人身攻击等不文明行为