SQL获取新插入行的标识数
2010-08-26 09:27
204 查看
对数据库操作时,需要保留刚插入的新行的标识列以备后用,下面是用SQL语句实现方法:
private SqlConnection connection;
//连接字符串
this.connection = new SqlConnection();
this.connection.ConnectionString =
@"Data Source=.;Initial Catalog=DBDemo;Persist Security Info=True;User ID=sa;Password=123";
this.connection.Open();
//SQL语句
SqlCommand command = new SqlCommand();
command.Connection = this.connection;
command.CommandType = CommandType.Text;
string sql = string.Format(
"insert into ……");
command.CommandText = sql;
//执行SQL语句
command.ExecuteNonQuery();
//获取标识列的SQL语句
string sequel = "SELECT @@IDENTITY"; //主要是这句
SqlCommand comm = new SqlCommand();
comm.Connection = this.connection;
comm.CommandType = CommandType.Text;
comm.CommandText = sequel;
//执行SQL语句,获取新插入行的标识列
object id = comm.ExecuteScalar();
介绍@@IDENTITY的文章可以从下面找到
http://baike.baidu.com/view/1592444.htm
private SqlConnection connection;
//连接字符串
this.connection = new SqlConnection();
this.connection.ConnectionString =
@"Data Source=.;Initial Catalog=DBDemo;Persist Security Info=True;User ID=sa;Password=123";
this.connection.Open();
//SQL语句
SqlCommand command = new SqlCommand();
command.Connection = this.connection;
command.CommandType = CommandType.Text;
string sql = string.Format(
"insert into ……");
command.CommandText = sql;
//执行SQL语句
command.ExecuteNonQuery();
//获取标识列的SQL语句
string sequel = "SELECT @@IDENTITY"; //主要是这句
SqlCommand comm = new SqlCommand();
comm.Connection = this.connection;
comm.CommandType = CommandType.Text;
comm.CommandText = sequel;
//执行SQL语句,获取新插入行的标识列
object id = comm.ExecuteScalar();
介绍@@IDENTITY的文章可以从下面找到
http://baike.baidu.com/view/1592444.htm
相关文章推荐
- sql获取受影响行数、插入标识值
- SQL语句中插入标识列获取标识ID的两种方式
- sql获取受影响行数、插入标识值
- SQL:插入指定标识列的数据时候的小错误
- sql 中获取最后生成的标识值 IDENT_CURRENT ,@@IDENTITY ,SCOPE_IDENTITY 的用法和区别
- ms sql server 在abator生成的 insert 无法获取插入 id 的原因
- 如何获取SQL Sever中自增长列的下一行标识值?(获取刚插入的标识值)
- 用sql脚本一条条导数据的两种方法,需返回唯一标识@@IDENTITY作为插入到第二个表用。
- thinkphp5 execute执行原生sql插入时获取最新进行新增插入的id
- C# 用SqlBulkCopy 批量插入oracle数据 遇到了 ORA-00054: 资源正忙, 但指定以 NOWAIT 方式获取资源, 或者超时失效
- Linq to SQL 插入和获取ID
- 获取SQL 下一条 将要插入数据 的 主键id 值
- php 获取mysql中插入的id 和 sql语句查看是否有重复
- 获取插入数据库记录的自动标识
- java.sql.SQLException: 当 IDENTITY_INSERT 设置为 OFF 时,不能为表 'TB_OTHER_AGENTPUTONREC' 中的标识列插入显式值。
- 获取某个表的数据,并产生插入这些数据的SQL(主要用于不同服务器间相同结构表的数据复制)。
- SQL中获取刚插入记录时对应的自增列的值
- SQL获取表中最新插入的记录
- 【SQL学习】获取表中字段的IDENT种子、增量、最新标识
- sql中插入一条记录并获取该条记录的自动增长ID