Resetting Indentity Columns
Nov 15, 1999I would like to reset the Identity column in a table so it starts at the begining. I am planning to clean out this table.
Thanks
Gary
I would like to reset the Identity column in a table so it starts at the begining. I am planning to clean out this table.
Thanks
Gary
Arkadiy writes "Why @@indentity returns NULL after inserting new row?"
View 6 Replies View RelatedHi folks!
I need to populate a table having an identity field with data (basically I want to make a copy of a table with identity column on another server). When I use BCP to insert data then the values in the identity field is not the same as in the data file but gets incremented from the original.
eg. if the records in the flat file are-
1, 'test1'
2, 'test2'
Now if i insert this into the table (say the last identity value was 100) then rows get inserted as-
101, 'test1'
102, 'test2'
Is there any way by which I can retain the values of the identity column to be same as in the file?
Thanks!
when I use the code
SET IDENTITY_INSERT tss_Cable ON
go
DECLARE @@nextidentval int
SELECT @@nextidentval = MIN(IDENTITYCOL) + IDENT_INCR(tss_Cable)
FROM tss_Cable t1
WHERE IDENTITYCOL BETWEEN IDENT_SEED(tss_Cable) AND 2147483646
AND NOT EXISTS (SELECT * FROM tss_Cable t2
WHERE t2.IDENTITYCOL = t1.IDENTITYCOL IDENT_INCR(tss_Cable))
go
SET IDENTITY_INSERT tss_Cable OFF
I get the following error.
error line 2 Incorrect syntax near IDENT_INCR.
error line 6 incorrent syntax near IDENT_INCR.
I would like to reset the identity without droping the table. I'm using
sql 6.5. I looked at Mark Lessard 12/17/99 respose on this issue and changed
the code to match his version but the same error occured.
How do reset identity seed on table, for example I have table that has gap in the identity such as (1,2,3,5,6, etc..) and I want reset the entire table.
Thank You,
John
What is the best way to do Indentity(1,1) on fields which is varchar(8)?
View 1 Replies View RelatedI'm doing a data transfer from Access to SQL Server, I wish to keep theidentity column (autonumber) values as all the data is already related. Itried the first table append query including the identity column, it worked.Was this fluke? Will it always work? I was under the impression that I wouldhave to issue a "set identity_insert on" before doing this. The SQL databasewill have absolutely no data before the transfer routines are run.
View 15 Replies View RelatedIDE: Visual Studio 2008
DB: SSCE 3.5
OS: WinXP SP2 (CHS)
.....
Code Snippet
String str_sql_insert = "INSERT INTO Person (Name, ShortName, Description, Tag) VALUES ('" + this.TextBox.Text.Trim() + "', '" + this.ShortNameTextBox.Text.Trim() + "', '" + this.DescriptionTextBox.Text.Trim() + "','" + this.TagComboBox.SelectedValue.ToString().Trim() + "); SELECT @@INDENTITY";
SqlCeConnection tempConn = dbman.getConn();
SqlCeCommand tempComm = new SqlCeCommand(str_sql_insert, tempConn);
tempConn.Open();
Object ob = tempComm.ExecuteScalar();
.....
When I run the application there is a error report on the last line of the code above:
[ Token line number = 1,Token line offset = 127,Token in error = SELECT ]
When I copy the SQL string into the QueryBuilder in the VS2008 it is works and returned a correct value.
I want to know is there something wrong with the sql string or the ExecuteScalar() cant execute 2 steps command?
thanks
As an example I have three tables
Table1
ChildName (nvarchar)30
ChildID (INT) Set as €˜IDENTITY€™
Table2
ParentName(nvarchar)30
ParentID (INT) Set as €˜IDENTITY€™
Table3
ChildID (INT)
ParentID (INT)
I have the following code.
Dim dbcnn As SqlClient.SqlConnection = New SqlClient.SqlConnection(dbsettings.getDatabaseString)
Dim dbcmd As SqlClient.SqlCommand
dbcmd_AddDriverRoute = New SqlClient.SqlCommand("usp_Insert", dbcnn)
dbcmd.CommandType = CommandType.StoredProcedure
dbcmd.Parameters.AddWithValue("@ChildID ", cmb_child.SelectedItem)
dbcmd.Parameters.AddWithValue("@ParentID ", "@@IDENTITY")
dbcnn.Open()
dbcmd.ExecuteScalar()
dbcnn.Close()
basically what I want to do is when a child is added I want to be able to insert ParentID (INT) Set as €˜IDENTITY€™ value into table3 ParentID (INT) .
I have my sql statement in place I am not sure how to take an identity value stored in the db.
i have table with one column
CREATE TABLE [dbo].[tblTest](
[ID] [int] IDENTITY(1,1) NOT NULL
how do i insert values.(i,e identity)
I'm trying something new, and have hit a snag.
basically, I'm attempting to use two INSERT commands in a single SP. I want to use the PK from the new entry and apply that to the second.
here's the code;
:::::::::::::::::::::::::::::::::::::::::::::::::: :::::::::::::::
CREATE PROCEDURE spInsertNewUser
@fn varchar(50),
@ln varchar(50),
@add varchar(50),
@add2 varchar(50),
@ct varchar(50),
@cty varchar(50),
@st varchar(4),
@pc varchar(50),
@ph varchar(50),
@cp varchar(50),
@fx varchar(50),
@em varchar(50),
@pw varchar(50),
@uid varchar(50),
@rc bit,
--@indentity int OUTPUT,
@cid int
AS
SET NOCOUNT ON
INSERT INTO tblUserInfo
(
firstName,
lastName,
address,
address2,
city,
county,
state,
postalCode,
phone,
cellPhone,
fax,
email,
pword,
userUID,
regConfirmed
)
VALUES (
@fn,
@ln,
@add,
@add2,
@ct,
@cty,
@st,
@pc,
@ph,
@cp,
@fx,
@em,
@pw,
@uid,
@rc
)
SELECT @@IDENTITY FROM tblUserInfo
--SET @indentity = @@IDENTITY
INSERT INTO tblUserToCountySubscribedLKP (
UserID, CountyID
) VALUES(
@@indentity, @cid
)
:::::::::::::::::::::::::::::::::::::::::::::::::: :::::::::::::::
I'm sure the problem is largely due to the fact that I am close to completely clueless on such things, but a bit of timely advice from the sage sql wizards here would be most welcome and greatly appreciated.
Hello folks,
I am using the following INSERT statement to add a new record in my table. I want to be able to get the Autonumber UserID field of the newly created record but I am getting the following error: "Characters found after end of SQL statement"
Code:
INSERT
INTO tblUser
(LoginName, UserPassword, EmailAddress, City)
Values
(@User, @UsrPassword, @EmailAddress, @City);
SELECT @@IDENTITY As 'Identity'
What is wrong in my statement?
How do I retrieve the Autonumber field of the newly created record?
How do I handle if the LoginName and/or EmailAddress already exists?
I want to be able save this INSERT statement as an Access Query and call it from my C# code.
I would appreciate any help.
Thanks
Mike
Hi Guys,
I'm using SQL server 2000.
How do I alter column/field from type int (with Identity = Yes Not For Replication) to just normail int field. No more identity. I want it to be done using SQL script( sql query analyzer).
Please help me on this, thx
Regards,
Shaffiq
I imported a table using DTS.
I run SQL statements in my original server database. It works well.
But when I run the same instructions within a stored procedure in my new workstation where I improrted the table I get this error:
Server: Msg 515, Level 16, State 2, Procedure InsertFichierPrix, Line 11
Cannot insert the value NULL into column 'Id', table 'myDBLive.dbo.FichierPrix'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Here is the SQL statements that I run on the original Database:
insert into fichierprix(nomfichier, version, descriptionfr, typeclient,....) values(@NomFichier,'Actuelle', @NomFourFr, 'MembreAcheteur', ....)
And here is my SP that I run on the new imported database:
CREATE PROCEDURE InsertFichierPrix @NomFichier varchar(50), @NomFr varchar(50),@NomAn varchar(50)
AS
declare @NomFourFr varchar(50)
declare @NomFourAn varchar(50)
SET @NomFourFr='liste fournisseur ' + @NomFr
set @NomFourAn='liste fournisseur ' + @NomAn
insert into fichierprix(nomfichier, version, descriptionfr, typeclient,...) values(@NomFichier,'Actuelle', @NomFourFr, 'MembreAcheteur'...)
GO
And here is the execution of my Stored proc on the destination database:
execute insertfichierprix @NomFichier='myfilename2', @NomFr='fournifr1',@NomAn='Fourniang1'
Thank you for helping me.
Hi,When i eg. manually ad entries to a table and, cancels the insert Ms SQLincrement the counter on the ID anyway. Is there a way to avoid thisbehavior?RegardsAnders
View 1 Replies View RelatedHi AllI have a table in SQL Server with ID having indentity inrement by one.Table has not any trigger. Frequently ID in the table jumps.Any help !!!Thanks
View 2 Replies View RelatedI am trying to remove the Indentity property from a column so I can do some clean up. Then will need to add it back. Adding Indentity property back is not a problem, but cant figure out how to remove it in the first place.
Any help would be greatly apprecaited.
Thanks
Dave
Hello, everyone:
I have a table with an indentity column as first column. At beginning it is continue such as 0-50. I delete last 20 columns by hand. The 0-31 is left. When the new data is inserted, I hope the new indentity column begin from 32. How to do that? Now the indentity column begin from 51 as the new data is inserted.
Thanks a lot
ZYT
Hi There
Can anyone tell me how an identity column decides what number to give which row.
I always thought that it was in order of the clustered index.
But i have found the following:
If you have Table A with a clustered index(not unique) say on the first 3 columns.
If the table is empty and you add an identity column, then afterward load it with data the value of the identity column seems to match the clustered index.
But if the table has no identity column and it is filled with data, and then you add an identity column the number for the identity column seems to be all over the place.
So basically how does a newly added identity column know what number to give each row, what if the clustered index is not unique? Is it random ?
Thanx
Dear Friends,
I need a SQL Query to add a identity coloumn for anExisting table. (ie) when i try to alter the table i want to add an identity coloumn.
Thanks in advance.
hi guys i was wondering if anyone could help me, i have a table with a field called id that did have numbers 1,2,3,4,5,6,7,8 and so on! but after some tinkering i have removed a few value and added more so i now have 1, 4,8,19,20 and so on!i was wondering if i can run a query to update those value and return them to 1,2,3,4,5,6,7,8 and so on?CheersTupps
View 2 Replies View RelatedHi,I have a table OutMailDetails with the following fields : OutMailID --- Foriegn Key Name Description
My problem is that i have datas already in this table and the table is related to another table called OutMail through OutMailID field. Please how can i make it (OutMailID field) a primary key now.
i am using autonumber as a primary key in one table. in my app., row from that table will be moved to another table after some time but that autonumber is important. when there are no any data in first table, and new row is inserted, autonumber starts from 1 which i don't want as there will be data redundancy when it will be moved to another table. so is there any way i can force the autonumber to start from previous value rathe than 1?
View 2 Replies View Relatedhi!i'm new to sql server and enterprise manager and i accidentally deleted all data in a table. how do i recover them? the table (CaptureManager) is still there but empty. i have the following information:if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CaptureManager]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[CaptureManager]GO
CREATE TABLE [dbo].[CaptureManager] ( [ID] [tinyint] IDENTITY (1, 1) NOT NULL , [Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [Email] [varchar] (75) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [Ext] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [Status] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) ON [PRIMARY]GO
Hey! I downloaded the sql engine and made a bunch of tables in visual basic. They were called new1, new2, new3, and new4. So I deleted new1.mdf, new1.ldf, new2.mdf, etc... but I notice I still can't recreate them. So I'm thinking there's remnants in master.mdf or something?? How would I go about getting rid of all the old tables, even ones whose names I've forgotten, so I can have a clean slate again? (btw I don't have sql server, just the desktop engine)
View 4 Replies View RelatedI am trying to reset an IDENTITY RowNumber
back to 1 in a query when the Person's Name is the same. The following query
can be used agains the pubs database in SQL Server.
I am trying to figure out where to place the section for the DBCC CHECKIDENT item in order to reset the RowNumber back to 1 when ever the lname column is the same. For example if the pub database had duplicate records for a given employee the RowNumber would reset back to 1.
CREATE TABLE #RowNumber (
RowNumber int IDENTITY (1, 1),
emp_id char(9) )
--DECLARE @seed int
--SET @seed = 1
--DBCC CHECKIDENT ('#RowNumber', RESEED , @seed) WITH NO_INFOMSGS
INSERT #RowNumber (emp_id)
SELECT emp_id
FROM employee
ORDER BY lname
SELECT RowNumber, e.emp_id, lname, fname, job_id
FROM #RowNumber r JOIN employee e
ON r.emp_id = e.emp_id
ORDER BY RowNumber
DROP TABLE #RowNumber
Ganesh
Hello all-
Is it possible to reset the values of DMV stats/counters without restarting the SQL service? I'm looking for something more than dbcc freeproccache...more along the lines of index_usage and some of the OS DMVs.
Cheers,
-Brandon Tucker
Hello all.
This is the best suited forum I found for my problem, if there's a better suited one please direct me.
I am running SQL Server 7.0 on Windows 2000 Server, and the SA's password has been forgotten and no other employee knows it.
I searched the net for a solution, and I found various pages describing how to reset the SA's password by logging in an administrator, connecting to the server and using a sp_password command.
For some reason, I cannot connect to the server even when I'm logged on as administrator.
Here are the steps I took:
1) I logged in as DOMAINAdministrator at my domain controller.
2) I opened Enterprise Manager and clicked on the server labeled "(LOCAL)". The server is registered to use "Windows NT authentication".
3) Received the following error:"A connection could not be established to (LOCAL) - Login failed for user 'DOMAINAdministrator'.. Please verify that SQL Server is running and check your SQL Server registration properties ... and try again". If there was an option to attach a screenshot, I would, but...
4) I have verified that SQL Server is running.
As I am new to SQL Server, I'm not sure about this, but the SQL Server is called SERVERNET, and the domain I'm logged into is called DOMAIN.
Should I login as an administrator to SERVERNET and not to DOMAIN? Is that possible? "SERVERNET" does not show on the login screen, only "DOMAIN" is listed there.
Any help will be appreciated.
Thanks
I've seen a lot of solutions to reset the an Identity Field, but the one I found in the website I mentioned worked fine in SQL 2005 Express Edition.
http://www.howtogeek.com/howto/database/reset-identity-column-value-in-sql-server/
The other solutions in SQL 2005 that use ALTER TABLE and ALTER COLUMN just don't work, I don't no Why.
Paulo Alexandre
If there are gaps ( due to deletions ) in indentity column, how do I
resequence the values ? As well as how to reset the last used number ?
Info. is greatly appreciated.
Ivan
What is the easiest way in T-SQL to reset the identity values of
the PK columns in a DB. Here's the scenario.
I'm going to be backing up a HUGE DB and then restoring
it to a new server. Once there I will run an SP to remove all the existing
data. The tables are now row-free. However my customer doesn't like that
the first record they add gets PK value of 5,321, or whatever.
After I remove all the data how can I reset the ids?
It would be nice to add some code to my sp_cleardb
that would go back and reset the identity columns
FYI
All of my tables use auto-incrementing identity fields with a seed of 1
1) I know how to do it in enterprise manager, but I need it in scripting
since I'll have to do it on hundreds of tables
2) I tried using alter table to drop the PK constraint, but that requires
knowing the pk constraint name, which is SQL generated and I won't know.
I think I got very close, but the code was just getting too big. I thought,
there must be an easier function to use, or a built in SP, or something?
Anyone know how to script this?
THanks in advance.
Josh
Question - if you had to completely strip all permissions from all databases in an instance and reset them, assuming you have metadata to support rebuilding the permissions, what steps would you follow? I can handle the iterating through each database, but at the database level, what steps would you take?
The reason I inquire on this is I currently have a job that I inherited that does just this. But it's buggy and was also written in for SQL Server 2000. With some of the changes in 2005, a few bugs have crept in, etc. And I would like to confirm my thoughts this. Or, if your opinion is why are you wasting your time on this? Then that's fine to and I'll review any constructive comments you may have.
Greetings,
I've run into an issue that's been driving me up a wall.
Running SQL Server 2005, two instances production and development, report server on each.
I have a multiple scheduled reports on each instance, and I've over wrote the report server subscription with a SQLAgent schedule.
For whatever reason the reports on the production instance keep having their schedule reset to the subscription when the report was first created.
The logs give me a warning that the schedule is changing or deleted but it's happening when no one is around.
Can anyone shed some light on this for me? or am I missing something really obvious here?
Thanks,
Erik