mssql2008 自訂表格類型實現(批量插入或者修改)_Mysql

來源:互聯網
上載者:User
在做大型網站或者系統的時候,經常會遇到個問題就是批量插入或者修改資料庫。如果遇到這個問題,還是一條條記錄來處理,這樣的效率太低了,所以要考慮批量插入或者修改

今天這邊不講SqlBulkCopy,只簡單講sql自訂表格類型。因為目前的項目我用到了分表的方式,用預存程序比較方便自動建立分表。現在把我目前寫的功能簡單做個記錄,也方便以後自己查閱

第一步,在資料庫裡點擊 建立查詢 建立相應的sql
複製代碼 代碼如下:

--======自訂表格類型Demo======
--建立表
create table tab
(
tabvalue varchar(10)
)
go
--建立自訂表格類型
create type Type_tab as table
(
Type_tabvalue varchar(10)
)
go
--建立 預存程序
create procedure p_Tab
(
@ptab Type_tab readonly
)
as
begin
insert into tab select * from @ptab
end
--sql 測試表類型 type1
declare @tt Type_tab
insert into @tt values('a')
insert into @tt values('b')
insert into @tt values('c')
insert into tab select * from @tt
select * from tab
--sql 測試表類型 type2
declare @tt2 Type_tab
insert into @tt2 values('a')
insert into @tt2 values('b')
insert into @tt2 values('c')
execute p_Tab @tt2

第二步 asp.net 調用 預存程序
複製代碼 代碼如下:

using (SqlConnection conn =SqlHelper.Settings.GetSqlConnection(true))
{
try
{
DataTable DtAdd = new DataTable();
DtAdd.Columns.Add("tabvalue");
DtAdd.Columns["tabvalue"].DataType = System.Type.GetType("System.String");
foreach (ModelEnt rl in List)
{
DataRow Dr = DtAdd.NewRow();
Dr["tabvalue"] = rl.tabvalue;
DtAdd.Rows.Add(Dr);
}
//int Rt = SqlHelper.SqlHelper.SqlBulkCopy(DtAdd, TableName, conn);
SqlCommand cmd = new SqlCommand("p_Tab", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ptab", SqlDbType.Structured).Value =DtAdd;
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
#if DEBUG
throw ex;
#else
return -10000;
#endif
}
finally
{
conn.Close();
}

ModelEnt 是tab表對應的實體類。list 是ModelEnt 的一個集合,這樣可以實現多個row,這樣就能一次插入多條記錄。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.