zoukankan      html  css  js  c++  java
  • 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");  
  • 相关阅读:
    全面认识golang string
    解决Manjaro Linux无法安装搜狗拼音
    解决QTableWidget不显示数据的问题
    在go modules中使用replace替换无法直接获取的package(golang.org/x/...)
    在go modules里使用go get进行包管理
    golang包管理解决之道——go modules初探
    反爬虫——使用chrome headless时一些需要注意的细节
    golang使用chrome headless获取网页内容
    <强化学习>开门帖
    <老古董>1992年之后的非线性支持向量机解法
  • 原文地址:https://www.cnblogs.com/swjian/p/6360290.html
Copyright © 2011-2022 走看看