MsSQL   发布时间:2022-05-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了SqlServer建立存储过程,方便.NET插入自增字段大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

首先,需要在数据库中创建一个表,以在test数据库创建tableNo表为例:

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建立存储过程,方便.NET插入自增字段全部内容,希望文章能够帮你解决SqlServer建立存储过程,方便.NET插入自增字段所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:首先