我正在尝试获取表image
的最后一个身份。
以下代码无效:
SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["DSN"]);
SqlCommand ident = new SqlCommand("SELECT IDENT_CURRENT(‘image’)", connection);
connection.Open();
id = Convert.ToInt32(ident.ExecuteScalar());
我需要这个,所以即使我删除最后一行,我也可以获得最后一个自动生成的身份。
答案 0 :(得分:1)
SELECT
SCHEMA_NAME( OBJECTPROPERTY( C.OBJECT_ID, 'SCHEMAID' )) AS [SCHEMA NAME],
OBJECT_NAME( C.OBJECT_ID ) AS [TABLE NAME], C.NAME AS [COLUMN NAME],
T.NAME AS [COLUMN DATA TYPE],SEED_VALUE,
INCREMENT_VALUE,LAST_VALUE AS CURRENTMAXVALUE
FROM SYS.IDENTITY_COLUMNS C INNER JOIN SYS.TYPES T ON C.USER_TYPE_ID = T.USER_TYPE_ID
WHERE COLUMNPROPERTY(OBJECT_ID, C.NAME, 'ISIDENTITY') = 1
AND LAST_VALUE IS NOT NULL
ORDER BY LAST_VALUE DESC
答案 1 :(得分:0)
对于MySQL,您的代码看起来应该可以工作。如果该命令不起作用,您会收到什么错误消息?
对于SQL Server,您可以从sys.identity_columns
表中检索最后生成的标识:
select last_value
where name = 'ColumnName'
and object_id = object_id('TableName')
答案 2 :(得分:0)
我的应用程序在服务器上传文件并将其保存到db并将其绑定到(GridView
并删除每行的链接)
如果我使用last_value,我每次都会得到相同的最后一个id
SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["DSN"]);
SqlCommand ident = new SqlCommand("select LAST_VALUE where name = 'Id' and object_id = object_id('image')", connection);
connection.Open();
id = Convert.ToInt32(ident.ExecuteScalar());
_fileName = fileName;
_fullFileName = _outputPath + (id + 1).ToString() + prefix + Path.GetFileName(_fileName);
_fs = new FileStream(_fullFileName, FileMode.Create);
我的问题是,当我在下面使用MAX(Id)
时,一切都很好,直到有人删除最后一行或MAX行时我失去了我的身份 - 这就是为什么我想要获得最后一次自动增量身份不是id列的最后一个值
SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["DSN"]);
SqlCommand ident = new SqlCommand("SELECT MAX(Id) from image", connection);
connection.Open();
SqlDataReader result = ident.ExecuteReader();
result.Read();
object obValue = result.GetValue(0);
id = Convert.ToInt32(obValue.ToString());
connection.Close();
答案 3 :(得分:0)
选择IDENT_CURRENT('image') - 1
假设你增加1