Reset Identity column to zero in SQL Server?

前端 未结 6 2294
不知归路
不知归路 2021-02-19 04:36

How can I reset the Identity column of a table to zero in SQL Server?

Edit:

How can we do it with LINQ to SQL ?

相关标签:
6条回答
  • 2021-02-19 04:41

    To accomplish the same task in a SQL Compact table use:

    db.CommandText = "ALTER TABLE MyTable ALTER COLUMN Id IDENTITY (1,1)";   
    db.ExecuteNonQuery(  );
    
    0 讨论(0)
  • 2021-02-19 04:42
    DBCC CHECKIDENT ( ‘databasename.dbo.yourtable’,RESEED, 0)
    

    More info : http://msdn.microsoft.com/en-us/library/ms176057.aspx

    0 讨论(0)
  • 2021-02-19 04:49

    Generic extension method:

        /// <summary>
        /// Reseeds a table's identity auto increment to a specified value
        /// </summary>
        /// <typeparam name="TEntity">The row type</typeparam>
        /// <typeparam name="TIdentity">The type of the identity column</typeparam>
        /// <param name="table">The table to reseed</param>
        /// <param name="seed">The new seed value</param>
        public static void ReseedIdentity<TEntity, TIdentity>(this Table<TEntity> 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);
        }
    

    Usage: myContext.myTable.ReseedIdentity(0);

    0 讨论(0)
  • 2021-02-19 04:54

    Use the LINQ to SQL ExecuteCommand to run the required SQL.

    db.ExecuteCommand("DBCC CHECKIDENT('table', RESEED, 0);");
    

    LINQ is a data-source agnostic query language and has no built-in facilities for this kind of data-source specific functionality. LINQ to SQL doesn't provide a specific function to do this either AFAIK.

    0 讨论(0)
  • 2021-02-19 05:01
    DBCC CHECKIDENT (MyTable, RESEED, NewValue)
    

    You can also do a Truncate Table, but, of course, that will remove all rows from the table as well.

    To do this via L2S:

    db.ExecuteCommand("DBCC CHECKIDENT('MyTable', RESEED, NewValue);");
    

    Or, you can call a stored procedure, from L2S, to do it

    0 讨论(0)
  • 2021-02-19 05:01

    use this code

    DBCC CHECKIDENT(‘tableName’, RESEED, 0)
    
    0 讨论(0)
提交回复
热议问题