您好,欢迎访问一九零五行业门户网

SQL自动增长列

在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 看到了这个行计数(即一行受到影响)并将其解释为表示一个记录集。因此,真正的数据被推回到了第二个记录集。
其它类似信息

推荐信息