Home Database Mysql Tutorial SQL自动增长列

SQL自动增长列

Jun 07, 2016 pm 03:12 PM
2 sql variable automatic

在SQL SERVER2K有1个变量和2个函数可以得到: IDENT_CURRENT() 返回为任何会话和任何作用域中的特定表最后生成的标识值。 SELECT @@IDENTITY 返回为当前会话的所有作用域中的任何表最后生成的标识值。 SCOPE_IDENTITY() 返回为当前会话和当前作用域中的任何表

在SQL   SERVER2K有1个变量和2个函数可以得到:  
  IDENT_CURRENT()   返回为任何会话和任何作用域中的特定表最后生成的标识值。   
  SELECT   @@IDENTITY   返回为当前会话的所有作用域中的任何表最后生成的标识值。  
  SCOPE_IDENTITY()   返回为当前会话和当前作用域中的任何表最后生成的标识值。

 

========================================================================================

 

如何插入一条记录获取插入后的自动增长ID列的方法.

主要介绍了如何在设定了自动增长ID列后添加一条数据后获取添加的自动增长的ID值方法.

这篇文章我写了一个使用企业库3.0的方法来获取自动增长ID列的方法,代码如下:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

using Microsoft.Practices.EnterpriseLibrary.Data;

using System.Data.Common;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        Database db = DatabaseFactory.CreateDatabase("SQLConnectionString");

        string strSql = @"INSERT INTO [BSA].[dbo].[BSA_MissionLog]

           ([a]

           ,[b])

     VALUES

           ('1'

           ,'1'

           )

 

select id = scope_identity()";//这里是最重要的一段话.

        DbCommand dbcomm = db.GetSqlStringCommand(strSql);

        DataSet ds = db.ExecuteDataSet(dbcomm);

        for (int i = 0; i

        {

            for (int j = 0; j

{

                Response.Write("第"+i+"行"+j+"列:"+ds.Tables[0].Rows[i][j].ToString());

}

        }

    }

}

 

下面的代码是使用ado.net 2.0的代码:

SqlConnection con = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=table1;Persist Security Info=True;User ID=sa;Password=sa");

        try

        {

            string strSql = @"INSERT INTO Log

           ([a]

           ,[b])

     VALUES

           ('1'

           ,'1')

 

select id = scope_identity()";

            con.Open();

            SqlCommand com = new SqlCommand(strSql, con);

            DataSet ds = new DataSet();

 

            SqlDataAdapter da = new SqlDataAdapter(com);

            da.Fill(ds);

            con.Close();

            for (int i = 0; i

            {

                for (int j = 0; j

                {

                    Response.Write("第" + i + "行" + j + "列:" + ds.Tables[0].Rows[i][j].ToString());

                }

            }

        }

        finally

        {

            con.Close();

        }

 

微软对这样的方法解释是:

 

此代码告诉 SQL Server 不要返回查询的行计数,然后执行 INSERT 语句,并返回刚刚为这个新行创建的 IDENTITY 值。da.Fill(ds)语句返回的记录集有一行和一列,其中包含了这个新的 IDENTITY 值。如果没有此语句,则会首先返回一个空的记录集(因为 INSERT 语句不返回任何数据),然后会返回第二个记录集,第二个记录集中包含 IDENTITY 值。这可能有些令人困惑,尤其是因为您从来就没有希望过 INSERT 会返回记录集。之所以会发生此情况,是因为 SQL Server 看到了这个行计数(即一行受到影响)并将其解释为表示一个记录集。因此,真正的数据被推回到了第二个记录集。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1263
29
C# Tutorial
1236
24
What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

gateio exchange official website entrance Sesame door gate official website entrance gateio exchange official website entrance Sesame door gate official website entrance Feb 21, 2025 pm 02:48 PM

As a leader in cryptocurrency trading, Gate.io offers a wide range of trading pairs, derivatives and financial services. The Chinese version of the website Sesame Open Door Gate is convenient for Chinese users and provides the same functions as Gate.io, but it is more suitable for Chinese people's habits. Users can access the Gate.io exchange or Sesame Open Gate official website through the designated website. Please be sure to keep your account information carefully and only visit the official website to ensure safety.

Basic concepts and usage analysis of SQL in Go language Basic concepts and usage analysis of SQL in Go language Mar 27, 2024 pm 05:30 PM

Basic concepts and usage of SQL in Go language SQL (StructuredQueryLanguage) is a language specially used to manage and operate relational databases. In Go language, we usually use SQL to perform database operations, such as querying data, inserting data, updating data, deleting data, etc. This article will introduce the basic concepts and usage of SQL in Go language, with specific code examples. 1. Connect to the database In Go language, we can use third-party libraries to connect data

gate official website login portal gate.io login web version gate official website login portal gate.io login web version Feb 18, 2025 pm 03:00 PM

As a digital asset exchange, Gate.io provides users with a convenient login process. To log in to Gate.io, visit its official website and click the "Login" button in the upper right corner. Then enter your email address or mobile phone number and password and perform two-factor authentication (2FA) verification as needed. After successfully logging in, you can manage your account balance, orders, and transaction activity through the Gate.io dashboard. To ensure account security, it is recommended to use a strong password and change it regularly, while enabling 2FA and taking care of phishing attempts.

How to interact with JSON data using SQL in Golang? How to interact with JSON data using SQL in Golang? Jun 03, 2024 am 11:47 AM

There are the following steps for interacting with JSON data through SQL in Golang: Use the json.Unmarshal function to parse JSON data into a Go structure and convert JSON to a structure. Use the database/sql package to access and operate SQL databases and perform operations such as inserts and queries. Combining the above steps, you can build an application based on SQL and JSON in Go to implement functions such as user registration and login.

An in-depth discussion of the similarities and differences between slices and variables in Go language An in-depth discussion of the similarities and differences between slices and variables in Go language Apr 02, 2024 pm 06:33 PM

Both slices and variables in Go refer to the underlying array, shared memory. Slices have a length and expandable capacity, whereas variables have a fixed length. Slices use pointer semantics and variables use value semantics. By selecting slices or variables according to your needs, you can write more flexible and efficient Go programs.

Detailed explanation of the definition and use of Go language variables Detailed explanation of the definition and use of Go language variables Mar 24, 2024 am 08:27 AM

Detailed explanation of the definition and use of Go language variables Go language is a statically typed system programming language that supports object-oriented, procedural and functional programming styles. In the Go language, variables are the most basic unit used to store data. They can store values ​​of various data types, such as integers, floating point numbers, strings, etc. This article will introduce in detail the definition and use of variables in the Go language and provide specific code examples. Definition of variables In the Go language, the keyword "var" is used to define variables. The syntax for variable definition is as follows: v

Top 10 trading app virtual currency platforms rankings: Top 10 trading platforms in 2025 Top 10 trading app virtual currency platforms rankings: Top 10 trading platforms in 2025 Feb 17, 2025 pm 04:00 PM

As of 2025, the world's leading virtual currency platforms include Coinbase, Binance, FTX, Kraken, Huobi, OKX, Gemini, KuCoin, Bybit and Bittrex. Coinbase has a wide range of cryptocurrency options and a user-friendly interface, while Binance offers a wide range of trading pairs and derivatives. FTX focuses on trading instruments and leverage options, while Kraken is known for its security, low fees and asset choices.

See all articles