用sql server 2005 CLR 实现一对多的数据插入(体演一下sql server 2005 )
问题:向一张一对多的数据表中一次性添加多条数据.
1,数据表结构如下:
id:主键自动生成
userid 用户名 ,
userlink 连接,
其中一个user 对应多个userlink
2.创建数据库项目,如下图
3.添加class,如下图
4.添加Stored Procedure
5.编码
[Microsoft.SqlServer.Server.SqlProcedure]
public static void sp_InsertUserLinks(string userid, string userlinks)
{
SqlPipe pipe = SqlContext.Pipe;
using (SqlConnection sqlConn = new SqlConnection("context connection = true"))
{
sqlConn.Open();
StringBuilder query = new StringBuilder();
string[] links = userlinks.Split(new char[] { ',' });
foreach (string link in links)
{
if (link.Length > 0)
{
query.AppendFormat("insert into [wangxt].[dbo].[userlink] values('{0}','{1}');", userid, link);
}
}
SqlCommand sqlCmd = new SqlCommand(query.ToString(), sqlConn);
pipe.ExecuteAndSend(sqlCmd);
}
}
public static void sp_InsertUserLinks(string userid, string userlinks)
{
SqlPipe pipe = SqlContext.Pipe;
using (SqlConnection sqlConn = new SqlConnection("context connection = true"))
{
sqlConn.Open();
StringBuilder query = new StringBuilder();
string[] links = userlinks.Split(new char[] { ',' });
foreach (string link in links)
{
if (link.Length > 0)
{
query.AppendFormat("insert into [wangxt].[dbo].[userlink] values('{0}','{1}');", userid, link);
}
}
SqlCommand sqlCmd = new SqlCommand(query.ToString(), sqlConn);
pipe.ExecuteAndSend(sqlCmd);
}
}
6.编译,部署
7.在sql Server 2005中测试