您好,欢迎访问一九零五行业门户网

将DataTable作为存储过程参数的用法

比较新奇的 用法 。 最近工作中写了几个 存储 过程 ,需要向 存储 过程 中传递字符串,因为 sql server 2000 中没有内置类于 split 的函数,只好自己处理,将前台数据集中的一列用逗号拆分存到一个 liststring 中,再转化为字符串传给 存储 过程 ,很是麻烦
比较新奇的用法。
最近工作中写了几个存储过程,需要向存储过程中传递字符串,因为sql server 2000中没有内置类似于 split 的函数,只好自己处理,将前台数据集中的一列用逗号拆分存到一个list中,再转化为字符串传给存储过程,很是麻烦。今天看了下sql server 2008的新特性,发现有表变量的使用,及其将datatable作为参数的用法,就尝试了一下,简单谈谈心得。
 示例代码下载
一、测试环境
1、windows server 2008 r2 datacenter
2、visual studio 2008 team system with sp1
3、sql server 2008 enterprise edition with sp1
由于是sql server 2008新特性,所以只能用2008。
二、测试概述
测试项目很简单,就是添加新用户
三、准备数据
1、建立数据库、表、类型、存储过程
代码
 1 if not exists(select * from dbo.sysobjects where id = object_id('users') and objectproperty(id, n'isusertable') = 1)
 2 begin
 3  create table dbo.users
 4  (
 5   userid int identity(-1, -1) not null,
 6   username varchar(20) not null,
 7   userpass varchar(20) not null,
 8   sex bit null,
 9   age smallint null,
10   constraint pk_users_userid primary key(userid)
11  )
12 end
13 if not exists(select * from sys.table_types where name = 'usertable' and is_user_defined = 1)
14 begin
15  create type usertable as table
16  (
17   username varchar(20) not null,
18   userpass varchar(20) not null,
19   sex bit null,
20   age smallint null
21  )
22 end
23 go
24
代码
 1 if exists(select * from dbo.sysobjects where id = object_id('sp_insertsingleuser') and objectproperty(id, n'isprocedure') = 1)
 2 begin
 3     drop procedure dbo.sp_insertsingleuser
 4 end
 5 go
 6 create procedure dbo.sp_insertsingleuser
 7 (
 8     @user usertable readonly
 9 )
10 as
11 
12 set xact_abort on
13 begin transaction
14 
15 insert into dbo.users(username, userpass, sex, age)
16 select username, userpass, sex, age from @user
17 
18 commit transaction
19 set xact_abort off
20 go
前台搭建好表单,后台主要是一个函数:
代码
1     public void fninsertsingleuser(datatable v_dt)
 2     {
 3         try
 4         {
 5             sqlconnection cn = new sqlconnection(conn);
 6             sqlcommand cmd = cn.createcommand();
 7             cmd.commandtype = commandtype.storedprocedure;
 8             cmd.commandtext = @sp_insertsingleuser;
 9             sqlparameter p = cmd.parameters.addwithvalue(@user, v_dt);
10 
11             dataset ds = new dataset();
12             sqldataadapter da = new sqldataadapter(cmd);
13             da.fill(ds);
14         }
15         catch (exception ex)
16         {
17             throw ex;
18         }
19     }
点击【添加】按钮时调用存储过程。测试是完成了
其它类似信息

推荐信息