July 28, 2005 at 1:06 pm
DECLARE @RecNum int
SET @RecNum = 1
July 28, 2005 at 1:17 pm
When you use EXEC or sp_executesql, the code actually executes in a separate SQL batch than the one issuing the EXEC or sp_executesql command. This means a single hash (#) won't be seen by your original batch (the stored procedure) because it's a local temporary table. If you want to go down this road, you'll need to use two hashes (##) in the name, making the temporary table a global one. Obviously, unless you take pains to generate different temporary table names, you can't have this stored procedure running more than one at a time.
K. Brian Kelley
@kbriankelley
July 28, 2005 at 2:09 pm
Thank you. Can this same trick be used for table variables? From what I understand, table variables are better than temporary tables. If I can use this trick for table variables, would a DROP TABLE command work to free up the global table variable?
July 28, 2005 at 2:41 pm
If you're using a table variable, the table variable is going to disappear when the stored procedure that defined it ends.
From BOL:
table variables are cleaned up automatically at the end of the function, stored procedure, or batch in which they are defined.
K. Brian Kelley
@kbriankelley
July 29, 2005 at 7:45 am
Try this example:
CREATE TABLE #temp
(
id int IDENTITY(1,1)
, mydata varchar(20)
)
DECLARE @seed int
SET @seed = 12345
DBCC CHECKIDENT ('#temp', RESEED , @seed) WITH NO_INFOMSGS
INSERT #temp (mydata) VALUES ('ABC')
SELECT * FROM #temp
DROP TABLE #temp
July 29, 2005 at 10:47 am
Thanks for the example. The DBCC CHECKIDENT command works when I run it as the sys admin, but not as the dbo of a database. Brian mentioned in another thread that for this DBCC call to work, the user running the script needs to have elevated permissions for the TempDB, which may be a security issue.
February 20, 2012 at 5:11 am
I tried the script as well. It works fine.
The only difference is my seed value comes from reading a table instead of a static value:
DECLARE @Seed int
SELECT @Seed=TableIdentity FROM TableData WHERE TableDataID = 1;
DBCC CHECKIDENT('Project', RESEED, @Seed) WITH NO_INFOMSGS
Thank you very much for tip. It really helps Me.
Felix
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy