如何将datatable传入存储过程中?

如何将datatable传入存储过程中


精慕HU
浏览 756回答 2
2回答

牛魔王的故事

一、测试环境 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 前台搭建好表单,后台主要是一个函数: 123456789101112131415161718public 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); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); } catch (Exception ex) { throw ex; } }

翻过高山走不出你

表结构CREATE TABLE [dbo].[loader] ([ID] [bigint] IDENTITY (1, 1) NOT NULL ,[truckID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,[billID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,[warehouseID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,[source] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,[type] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,[forweight] [float] NULL ,[startweight] [float] NULL ,[endweight] [float] NULL ,[weight] [float] NULL ,[loadtime] [datetime] NULL) ON [PRIMARY]下面是存储过程存储过程主要实现按车号和日期查询记录CREATE PROCEDURE proc_Query@StartTime datetime,@EndTime datetime,@TruckNumber varchar(50)asselect * from loader where truckID = @TruckNumber and loadtime between @StartTime and @EndTime+1GO
打开App,查看更多内容
随时随地看视频慕课网APP