SQL批量更新操作[转载]

之前有提過一個方式來批量更新DB的資料,就是利用分隔符號把所有資料合併成單一字串,然後傳送此字串給SQL Server去轉換成表格做進階運用,今天就來看一下該如何利用此方式。

首先建立一個方法(Method)把要批量更新的資料組合成一個字串,你可以建立屬於自己的方法,這邊我用下面的範例說明。

0 1 public static string JoinList<T>( string delimiter, IEnumerable<T> items, Converter<T, string> converter)
0 2 ... {
03     StringBuilder builder = new StringBuilder();
04     foreach (T item in items)
05     ...{
06         builder.Append(converter(item));
07         builder.Append(delimiter);
08     }

09     if (builder.Length > 0)
10         builder.Length = builder.Length - delimiter.Length;
11
12     return builder.ToString();
13 }

此方法可以接受不同的資料型態然後轉成字串輸出,其使用方法如下:

List< int> lstCustomerID = new List< int> { 1001, 1002, 1003, 1004 };
//使用","作為分隔字元,輸入的資料型態為int
string strParameter = JoinList< int>( ",", lstCustomerID, delegate( int item) ... { return item.ToString(); });

幫然也可以輸入其他的資料型態如下

//一樣建立一個List<Guid>物件
List<Guid> lstCustomerID = new List<Guid> ... { guid1, guid2, ... };
//使用","作為分隔字元,輸入的資料型態為Guid
string strParameter = JoinList<Guid>( ",", lstCustomerID, delegate(Guid item) ... { return item.ToString(); });

此字串內容會是這樣

1001,1002,1003,1004

將此字串送入後端的SQL資料庫後,資料庫需要有function把此字串轉成資料表以利運用,下面是一個範例如何將此類字串轉成table。

0 1 CREATE FUNCTION dbo.fxnParseCommaDelmitedList
0 2 (
0 3 @CommaDelimitedList varchar(8000)
0 4 )
0 5 RETURNS @TableVar TABLE (ItemID int NOT NULL )
0 6 AS
0 7 BEGIN
0 8   DECLARE @IDListPosition int
0 9   DECLARE @IDList varchar(4000)
10   DECLARE @ArrValue varchar(4000)
11   SET @IDList = COALESCE(@CommaDelimitedList, '')
12   IF @IDList <> ''
13   BEGIN
14   --先在字串最後補上一個','
15   SET @IDList = @IDList + ','
16   WHILE PATINDEX( '%,%' , @IDList ) <> 0
17       BEGIN
18     SELECT @IDListPosition = PATINDEX( '%,%' , @IDList)
19     SELECT @ArrValue = LEFT(@IDList, @IDListPosition - 1)
20     --將分割後的數值存入@TableVar
21     INSERT INTO @TableVar (ItemID) VALUES ( CONVERT( int, @ArrValue))
22     --將已經處理過的字串移除
23     SELECT @IDList = STUFF(@IDList, 1, @IDListPosition, '')
24       END
25   END
26   RETURN
27 END

建立上面這個function並放在Table-Valued的資料夾下即可。

使用方式:

Select *
From dbo.fxnParseCommaDelmitedList(@parameter)

就會得到如下的表格

ItemID
1001
1002
1003
1004
原文: http://www.dotblogs.com.tw/kennyshu/archive/2009/07/12/9449.aspx
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值