SqlServer建立存储过程,方便.NET插入自增字段
2017-02-04 22:53
274 查看
首先,需要在数据库中创建一个表,以在test数据库创建tableNo表为例:
然后在数据库中 --> 可编程性 --> 存储过程 --> 新建存储过程 ,也可以在sql中执行代码如下:
其次在.NET中的DAL层创建一个CommonService类,代码如下:
using System.Data;
using System.Data.SqlClient;
应用方法如下:
create table tablesNo ( tableName varchar(30) not null, --表名 num int not null --行数 )
然后在数据库中 --> 可编程性 --> 存储过程 --> 新建存储过程 ,也可以在sql中执行代码如下:
USE [test] --数据库名 GO /****** Object: StoredProcedure [dbo].[usp_Id] Script Date: 2017/2/1 星期三 下午 6:48:47 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO create proc [dbo].[usp_Id] --新建一个存储过程名为usp_Id @tableName nvarchar(50), @id int output as declare @erro int set @erro=0 begin transaction select @id=num+1 from tablesNo where tableName=@tableName set @erro=@erro+@@ERROR update tablesNo set num=num+1 where tableName=@tableName set @erro=@erro+@@ERROR if(@erro=0) begin commit transaction end else begin rollback transaction end
其次在.NET中的DAL层创建一个CommonService类,代码如下:
using System.Data;
using System.Data.SqlClient;
public class CommonService { public static int GetId(string tableName) //存储过程ID { int id = 0; string sql = "usp_Id"; SqlParameter par1 = new SqlParameter("@tableName", tableName); par1.Direction = ParameterDirection.Input; SqlParameter par2 = new SqlParameter("@id", SqlDbType.Int); par2.Direction = ParameterDirection.Output; SqlConnection con = null; SqlCommand cmd = null; try { con = SqlHelper.Open(); cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandText = sql; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(par1); cmd.Parameters.Add(par2); cmd.ExecuteNonQuery(); id = Convert.ToInt32(cmd.Parameters["@id"].Value); } catch (SqlException ex) { } finally { con.Close(); } return id; } }
应用方法如下:
Id = CommonService.GetId("ClickAccessAmount");
相关文章推荐
- sqlserver使用户只能在某个架构下建立表和存储过程
- mybatis插入一个对象后获取表中自增的主键Id并且传入到插入的的对象中,方便将对象中其他属性赋值给其他以前表主键Id作为非空字段的表
- sqlserver 2008 R2 方便插入多行数据
- mssql 和 mysql的区别,让自动增长列自动递增就必须指定其他列名,mysql创建事务,如果插入的字符多余字段的值,会报错?截取插入?带输出参数的存储过程,带If else判断
- sqlserver常用sql语句,更改字段,建立唯一键,多个字段去重复等
- 在.net下如何获取刚插入SQLServer数据库的标识字段的值
- sqlserver 2008 R2 方便插入多行数据
- SqlServer判断数据库、表、字段、存储过程、函数是否存在
- mybatis插入一个对象后获取表中自增的主键Id并且传入到插入的的对象中,方便将对象中其他属性赋值给其他以前表主键Id作为非空字段的表
- 关于使用Visual Studio 2008 建立Setup And Deployment Project(安装与部署项目)制作安装.net 安装程序,插入Custom Actions(自定义动作)的办法
- sqlserver 2008 R2 方便插入多行数据
- SqlServer判断数据库、表、字段、存储过程、函数是否存在
- SqlServer 将存储过程查询的数据插入一张表
- ORACLE数据库中为每个数据表建立序列字段插入值的触发器的SQL脚本
- Sqlserver 查找存储过程,函数中是否存在某字段
- sqlserver 2008 建立订阅发布时 报错 解决方案 “错误 2812” 无法创建存储过程
- sqlserver常用sql语句,更改字段,建立唯一键,多个字段去重复等
- 请教:数据库字段类型为datatime,请问在.net里怎样转换为datetime类型来插入数据库?
- mysql建立存储过程,模拟插入200万用户
- SQLSERVER自动编号字段的插入