SQL自动增长列
Jun 07, 2016 pm 03:12 PM在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 看到了这个行计数(即一行受到影响)并将其解释为表示一个记录集。因此,真正的数据被推回到了第二个记录集。

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What is the difference between HQL and SQL in Hibernate framework?

Usage of division operation in Oracle SQL

What does the identity attribute in SQL mean?

Comparison and differences of SQL syntax between Oracle and DB2

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags
