在SQL Server中将标识列重置为零?
如何在SQL Server中将表的标识列重置为零?
编辑:
我们怎么能用LINQ to SQL做到这一点?
DBCC CHECKIDENT (MyTable, RESEED, NewValue)
您也可以执行截断表,但是,当然也会删除表中的所有行。
要通过L2S执行此操作:
db.ExecuteCommand("DBCC CHECKIDENT('MyTable', RESEED, NewValue);");
或者,您可以从L2S调用存储过程来执行此操作
DBCC CHECKIDENT ( 'databasename.dbo.yourtable',RESEED, 0)
更多信息: http : //msdn.microsoft.com/en-us/library/ms176057.aspx
使用LINQ to SQL ExecuteCommand运行所需的SQL。
db.ExecuteCommand("DBCC CHECKIDENT('table', RESEED, 0);");
LINQ是一种与数据源无关的查询语言,没有针对此类数据源特定function的内置工具。 LINQ to SQL不提供执行此操作的特定functionAFAIK。
通用扩展方法:
/// /// Reseeds a table's identity auto increment to a specified value /// /// The row type /// The type of the identity column /// The table to reseed /// The new seed value public static void ReseedIdentity(this Table table, TIdentity seed) where TEntity : class { var rowType = table.GetType().GetGenericArguments()[0]; var sqlCommand = string.Format( "dbcc checkident ('{0}', reseed, {1})", table.Context.Mapping.GetTable(rowType).TableName, seed); table.Context.ExecuteCommand(sqlCommand); }
用法: myContext.myTable.ReseedIdentity(0);
使用此代码
DBCC CHECKIDENT('tableName', RESEED, 0)
要在SQL Compact表中完成相同的任务,请使用:
db.CommandText = "ALTER TABLE MyTable ALTER COLUMN Id IDENTITY (1,1)"; db.ExecuteNonQuery( );