I have a T-SQL table variable (not a table) which has an auto incrementing identity column. I want to clear all data from this variable and reset the identity column value to 1. How can this be done?
相关问题
- sql execution latency when assign to a variable
- What is the best way to cache a table from a (SQL)
- php PDO::FETCH_ASSOC doesnt detect select after ba
- Bulk update SQL Server C#
- SQL to Parse a Key-Value String
相关文章
- Entity Framework 4.3.1 failing to create (/open) a
- How to truncate seconds in TSQL?
- Code for inserting data into SQL Server database u
- Delete Every Alternate Row in SQL
- Linux based PHP install connecting to MsSQL Server
- SQL Azure Reset autoincrement
- How do we alias a Sql Server instance name used in
- Is recursion good in SQL Server?
I suggest you use two table variables. The @Table1 has an identity seed on the first column. @Table2 has the same first column but no identity seed on it.
As you loop through your process,
then Delete From both Tables as your Process Loops.
On your first pass, the @Table2 will have a a sequential number in the first row starting at 1.
The second time through the loop your second table might have sequential numbers in the first column starting at say 1081. But if you select the minimum value to a variable
Then you can update @Table2 to make RowID start at 1 as follows:
Hope this helps
If you need to truncate the table variable in each turn of a while loop, you can put the
declare @myTbl (...)
statement in the loop. This will recreate the table and reset the identity column on each turn of the loop. However, it has a heavy performance hit. I had fairly tight loop, and redeclaring the table variable relative todelete @myTbl
was several times slower.Truncating the table will dump ALL the data, and reset the identity seed.
Otherwise, you can use this call to reset the identity while retaining any of the data:
I did this when I wanted to use a TOP and a variable when using SQL 2000. Basically, you add in the records and then look at the minimum one. I had the same problem and noticed this thread. Deleting the table doesn't reset the seed although I imagine using GO should drop the table and variable to reset the seed.
@maxlimit in the query above was to get the top 900 of the query and since the table variable would have a different starting identity key, this would solve that issue.
Any subsequent query can subtract that derived procedure to make it insert as "1", etc.
If you're using a table variable, you can't do it. If it were a table, you could truncate it or use
DBCC CHECKIDENT
. But, if you have to use a table variable, you have to use something other than an identity column. Or, more accurately, use the identity column in your table variable but output usingROWNUMBER
:It's the best you can do with the table variable.