示例代码下载
一、测试环境
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、建立数据库、表、类型、存储过程
代码如下:
IF NOT EXISTS(SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('Users') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE dbo.Users
(
UserID INT IDENTITY(-1, -1) NOT NULL,
UserName VARCHAR(20) NOT NULL,
UserPass VARCHAR(20) NOT NULL,
Sex BIT NULL,
Age SMALLINT NULL,
CONSTRAINT PK_Users_UserID PRIMARY KEY(UserID)
)
END
IF NOT EXISTS(SELECT * FROM sys.table_types WHERE name = 'UserTable' AND is_user_defined = 1)
BEGIN
CREATE TYPE UserTable AS TABLE
(
UserName VARCHAR(20) NOT NULL,
UserPass VARCHAR(20) NOT NULL,
Sex BIT NULL,
Age SMALLINT NULL
)
END
GO
代码如下:
IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('sp_InsertSingleUser') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
DROP PROCEDURE dbo.sp_InsertSingleUser
END
GO
CREATE PROCEDURE dbo.sp_InsertSingleUser
(
@User UserTable READONLY
)
AS
SET XACT_ABORT ON
BEGIN TRANSACTION
INSERT INTO dbo.Users(UserName, UserPass, Sex, Age)
SELECT UserName, UserPass, Sex, Age FROM @User
COMMIT TRANSACTION
SET XACT_ABORT OFF
GO
前台搭建好表单,后台主要是一个函数:
代码如下:
public void fnInsertSingleUser(DataTable v_dt)
{
try
{
SqlConnection cn = new SqlConnection(CONN);
SqlCommand cmd = cn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = @"sp_InsertSingleUser";
SqlParameter p = cmd.Parameters.AddWithValue("@User", v_dt);
10
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
}
点击按钮时调用存储过程。测试是完成了 猜你喜欢