如何在sql中获取下一个autoincrement值 [英] how to get the next autoincrement value in sql

查看:73
本文介绍了如何在sql中获取下一个autoincrement值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用c#创建一个Winform应用程序,并使用sql数据库.

I am creating a winform application in c#.and using sql database.

我有一张表 employee_master ,其中有诸如 Id,姓名,地址电话号码之类的列. Id 是自动递增,所有其他数据类型是 varchar .

I have one table, employee_master, which has columns like Id, name, address and phone no. Id is auto increment and all other datatypes are varchar.

我正在使用此代码获取下一个自动增量值:

I am using this code to get the next auto increment value:

string s = "select max(id) as Id from Employee_Master";
SqlCommand cmd = new SqlCommand(s, obj.con);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int i = Convert.ToInt16(dr["Id"].ToString());
txtId.Text = (i + 1).ToString();

我正在显示在文本框上.

I am displaying on a textBox.

但是当删除表中的最后一行时,我仍然会得到最近在文本框中删除的那个值

But when last row from table is deleted, still I get that value which is recently deleted in textbox

我应该如何获得下一个自动增量值?

How should I get the next autoincrement value?

推荐答案

要从SQLServer获取下一个自动增量值:

To get the next auto-increment value from SQLServer :

这将获取当前的自动增量值.

This will fetch the present auto-increment value.

SELECT IDENT_CURRENT('table_name');

下一个自动增量值.

SELECT IDENT_CURRENT('table_name')+1; 

------>即使添加一行然后将其删除,这也将起作用,因为IDENT_CURRENT返回在任何会话和任何作用域中为特定表生成的最后一个标识值.

------> This will work even if you add a row and then delete it because IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.

这篇关于如何在sql中获取下一个autoincrement值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆