T-SQL (SS2K8) :: How To Update Identity Column With Identity Value
Jan 25, 2015
I have table of three column first column is an ID column. However at creation of the table i have not set this column to auto increment. Then i have copied 50 rows in another table to this table then set the ID column values to zero.
Now I have changed the ID column to auto increment seed=1 increment=1 but the problem is i couldn't figure out how to update this ID column with zero value set to each row with this auto increment values so the ID column would have values from 1-50. Is there a away to do this?
Hi, I am having problem in bulk update of a sql server table haning identity column from a datatable( has no identity column) using sqlbulkcopy. I tried several approaches, but it does not show any error nor is the table getting updated. But the identity value seems to getting increased every time. thanks. varun
How to merge the data from one database to another if we have identity column on both the database. If we are merging two companies,we need employee table of 2 database and insert them into first database and corresponding fkey tables say some 7 tables.how to merge if the table is having identity column.
Ok,I just need to know how to get the last record inserted by the highestIDENTITY number. Even if the computer was rebooted and it was twoweeks ago. (Does not have to do with the session).Any help is appreciated.Thanks,Trint
i got a little problem. when i insert values into a table a trigger is launched wich updates something in the table too.
CREATE TRIGGER T1 ON Tbl FOR INSERT AS BEGIN IF (UPPER(USER) <> 'CONVERSIE') BEGIN UPDATE Tbl SET Datum = GetDate(), User = USER, WHERE Tbl.ID= (SELECT ID FROM inserted) END END
the error i receive is this: 'can not update identity column id' (id being pk).
I have a frustrating problem occuring in Sql 2005. We have the need in a few client upgrade situations to update the indentity column of a common resource table. It is populated each release with common records and the keys got out of sync for two releases due to developer error.
In Oracle this is not a problem. In SQL we get the message "Cannot update identity column 'mycolumn'". To get around this in SQL 2000 we updated the table by running the following.
exec sp_configure 'allow update', 1 go reconfigure with override go update syscolumns set colstat = colstat - 1 where id = object_id(Event') and name = 'EventKey' go exec sp_configure 'allow update', 0 go reconfigure with override go
In SQL 2005 this gives us the error
'Ad hoc updates to system catalogs are not allowed'.
Now I understand the need to keep people out of the system tables. However, can I have some sort of solution to this problem. I'm running a bunch of ad hoc queries to update the values and I don't want to create an exact duplicate of the table and copy over the information with the changes. It is much easier to run a simple update.
I set up replication on my DB between two server. The Publisher will not update tables on the Subscriber that use an identity column and I get an error "8102:cannot update identity column". I have looked around and can't seem to locate any solid fixes. If I remove the identity column from the subscribers tables the package works, but I am not able to use the DB on the subscriber because I need the Identity columns for my app to function properly. My Publisher and Subscriber are both running SQL Server 2000 Standard Edition SP3.
I'd set up Transactional Replication btw 2 servers running on MSSQL 2000.
However, from time to time, I encounter Error 8102. I try to reinitialise the subscription but failed. After I delete the current subscription and PUSH a new one, it will works fine again.
I'm curious why this is happening as I'd already set all the tables (articles) in the subscriber to "YES, not_for_replication".
We need to import data from flat/xml files into our database. we plan to do so in bulk as amount of data is huge, 2GB+ we need to do some validation checks in our code after that we create insert queries.
We have identity columns that are used as foreign keys in child tables. Question is how can I write a bulk/batch insert statement that will propogate the identity column to the child, as for all other we are creating the query in the application memory. there are 2 parent tables and 1st table value needs to be referred to in 7 tables and second table's value in 6.
when i alter non identity column to identity column using this Query alter table testid alter column test int identity(1,1) then i got this error message Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'identity'.
My current proc updates(updates using joins of two or three tables) millions of records as per the condition provided for each department.
However, when the proc fails it writes to a ErrorTable, ERROR_MESSAGE(), ERROR_SEVERITY() and which department has failed.
Since the records are updated keeping the selected departments in loop, I get the department in a temp variable.Now, I was asked to log the specific record where the failure was occured.Something like log the identity column value or primary key value which record has failed.
I add new records to a table with ADO. The tables contain an auto-increment identity column. I want to retrieve the identity value after the insert operation. This works fine for SQL Server 2000. On SQL Server 2005 this only works if I use a table in the select statement. If I use a view in the select statement, ADO returns no value for the identity column, a trace with profiler shows that there is no Select @@IDENTITY statement.
What is the reason for this behavior?
How can I change this behavior in SQL 2005 so that the behavior is the same as in SQL Server 2000?
I'm working with a third-party database (SQL Server 2005) and the problem here is the following:
- There are a bunch of ETL processes that needs to insert rows on a table (let's call this table T) and at the same time, an ERP (owner of T) is up and running (reading, updating and inserting on T).
- The PK of T is an Integer.
Today all ETL processes uses (select max(ID) + 1 from T) to insert new rows, so just picture the scenario. It is a mess! Everyday they get duplicate key error when 2 or more concurrent processes are trying to insert a row (with the max) at the same time.
Considering that I can't change the PK, what is the best approach to solve this problem?
To sum up:
* I need to have processes in parallel inserting on T
I have a four tables called plandescription, plandetail and analysisdetail. The table plandescription has the columns DetailQuestionID which is the primary and identity column and a QuestionDescription column.
The table plandetail consists of the column PlanDetailID which the primary and identity column, DetailQuestionID which is the foreign key attribute of plandescription table and a planID column.
The third table analysisdetail consists of a analysisID which the primary and identity column, PlanDetailID which is the foreign key attribute of plandetail table and a scenario.
Below is the schema of the three tables
I have a two web form that will insert, update and delete data into these three tables in a two transaction. One web form will perform CRUD operations in plandescription and plandetail table. When the user inserts QuestionDescription and planid in this web form, I will insert the QuestionDescription Value in the plandescription table and will generate a DetailQuestionID value and this value is fed to the plandetail table with the planid. Here I will generate a PlanDetailID.
Once this transaction is done, I will show the second web form in which the user enters the scenario and this will be mapped with the plandescription using the PlanDetailID.
This schema cannot be changes as this is the client requirement. When I insert values I don’t have any problem. However when I update existing data, I need to delete existing PlanDetailID in the plandetail table and recreate PlanDetailID data for that DetailQuestionID and planID. This is because, the user will be adding or deleting a planID associated with the QuestionDescription.
Once I recreate PlanDetailID for that DetailQuestionID and planID, I need to update the old PlanDetailID with the new PlanDetailID in the third table analysisdetail for the associated analysisID.
I created a #Temp table called #DetailTable to insert the values analysisID, planid and old PlanDetailID and new PlanDetailID so that I can have them in update statement once I delete the data from plandetail table for that PlanDetailID.
Then I deleted the plandetailid from the plandetail table and recreate PlanDetailID for that DetailQuestionID. During my recreation I fetched the new PlanDetailID’s created into another temp table called #InsertedRows
After this I am running a while loop to update the temp table #DetailTable with the newly created PlanDetailID for the appropriate planID’s. The problem is here. When I have the same number of planID’s for example 2 planID’s 1,2 I will have only two old PlanDetailID and new PlanDetailID for that planID and analysisID.But When I add a new PlanID or remove a existing planID I am getting null value for that newly added or deleted planID. This is affecting my update statement of analysisdetail table as PlanDetailID cannot be null.
I tried to remove the Null value from the #DetailTable by running the update statement of analysis detail in a while loop however its not working.
DECLARE @categoryid INT = 8 DECLARE @DetailQuestionID INT = 1380 /*------- I need the query to run for the below three data. Here i'm updating my planids that already exists in my database*/ DECLARE @planids VARCHAR(MAX) = '2,4,5'
While I have learned a lot from this thread I am still basically confused about the issues involved.
.I wanted to INSERT a record in a parent table, get the Identity back and use it in a child table. Seems simple.
To my knowledge, mine would be the only process running that would update these tables. I was told that there is no guarantee, because the OLEDB provider could write the second destination row before the first, that the proper parent-child relationship would be generated as expected. It was recommended that I create my own variable in memory to hold the Identity value and use that in my SSIS package.
1. A simple example SSIS .dts example illustrating the approach of using a variable for identity would be helpful.
2. Suppose I actually had two processes updating these tables, running at the same time. Then it seems the "variable" method will also have its problems. Is there a final solution other than locking the tables involved prior to updating them or doing something crazy like using a GUID for the primary key!
3. We have done the type of parent-child inserts I originally described from t-sql for years without any apparent problems. (Maybe we were just lucky.) Is the entire issue simply a t-sql one or does SSIS add a layer of complexity beyond t-sql that needs to be addressed?
We are in the conversion process of making the database ints.This is a change from a guid PK to an integer based PK that uses an int Identity. The program still uses the guid, and we are trying to map that guid to the databases int.We insert using TVPs passed from code. Since the identity is being set upon insert I have three things to accomplish:
1) Insert all the data into the dbo table 2) Update the parent Id in the table 3) Pass the SetsId guid, Sets_Id int, ParentSets_Id int back to the program
This is a high transaction table that will have a lot of records (millions).
--Sample table creation. There is a FK between Sets_Id to ParentSets_Id, Clustered PK on the Sets_Id IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[JSets]') AND type in (N'U')) BEGIN CREATE TABLE [dbo].[JSets]( [SetsID] [uniqueidentifier] NOT NULL, [Sets_Id] bigint Identity (1,1) NOT NULL,
I want to insert a new record into a table with an Identity field and return the new Identify field value back to the data stream (for later insertion as a foreign key in another table).
What is the most direct way to do this in SSIS?
TIA,
barkingdog
P.S. Or should I pass the identity value back in a variable and not make it part of the data stream?
I am working on a project to consolidate 3 distinct buildings name code(6 digit character called BUILDING_CODE Primary Key) into one building code. This is an effort to merge/move everyone who is currently coded under the three building codes into one building code. We currently have this column defined on 5 tables as primary key (none identity) in SQL Server 2005.
Out of the five tables one has two store procedure dependencies.
What would be the best practice to update the six digit BULDING_CODE column Primary Key value without causing any issues?
I have been trying to get the new sol_id that is added so I can use it in other code, but it is only returning 0. The new record is getting added to the table, but my varaiable myNewSolID is 0 in my response.write(myNewSolID) I appeaciate any help! Here is my steored procedure and my code: ALTER PROCEDURE [dbo].[AddTrackings]
@DropDate datetime, @Comment nvarchar(100), @DateEntered datetime, @EnteredBy nvarchar(50), @Sol_ID Int OUTPUT AS INSERT INTO tblTrackings (DropDate, Comment, DateEntered, EnteredBy)
Dim ConnectStr As String = _ ConfigurationManager.ConnectionStrings("2ConnectionString").ConnectionString
Dim MySQL As String = ""
If Me.chkDropSave.Checked Then MySQL = "AddTrackings" Dim MyConn As New SqlConnection(ConnectStr) Dim Cmd As New SqlCommand(MySQL, MyConn) Cmd.CommandType = CommandType.StoredProcedure Dim InsertedInteger As New SqlParameter("@Sol_ID", SqlDbType.Int) InsertedInteger.Direction = ParameterDirection.Output Cmd.Parameters.Add(InsertedInteger)
Dim MySqlParamStart As New SqlParameter("@DropDate", SqlDbType.DateTime) Cmd.Parameters.Add(MySqlParamStart) MySqlParamStart.Value = Me.BasicDatePickerDropDate.SelectedValue
Dim MySqlParamAmtTo As New SqlParameter("@Comment", SqlDbType.NVarChar, 100) Cmd.Parameters.Add(MySqlParamAmtTo) MySqlParamAmtTo.Value = Me.txtComment.Text
Having an identity column in target table, how do I use SQL 7 DTS ?
In Import wizard, I chose 'ignore' in source, checked Enable Indenity Insert - DTS failed with a msg like - a column cannot have NULL...
In DTS package, had Fast load and Enable Indenity checked - no luck !
Unchecked Enable identity, do luck.
What would be the standard procs for this since this sounds like a very common senario. What I am expecting is to insert from source and SQL would take care identity column automatically. Appreciate your help very much !
I want to know how to reset the identiy column when i delete a row from the existing table.
Example:
I have a table a with id (identity incr value 1) and name
I have 10 records inserted into it.,which would be from 1...thru...10 i delete a record say 5 then i have 1,2,3,4,6,7,8,9,10, now i want them to be rearranged to systamatic order like 1,2,3,4,5,6,7,8,9 how can i do this.
I have a table that has a field that will not accept null values. I was trying to create a new table with a new field that would accept null values. I would then drop the original table and rename the new table. The problem is my key field has the Identity column (Autonumber) turned on. This allows the recordID to be automatically generated. Is there anyway to bypass the Identity Column feature and still keep it there future records? I already tried the "with Nocheck Clause" but does not work.
How does one bcp data INTO a MS SQL Server table that includes an IDENTITY column from a text file that does NOT include a value for the IDENTITY column? Surely, this must be a common process?
Kudos to y'all! On most of my tables, I'm using a column of data type numeric and properties set as Identity with no replication. Now I know that it can handle only a length of 9 and obviously not nullable. Now by length of 9, does it mean in bytes or literal digits. If it is, then that would mean that it would reach only up to 999,999,999. What happens then if it reaches that digit?
How do you insert into a table that has an identity column aset of rows with predefined values for the identity column. I have tried to Set Identity_insert off and then insert but it didnt work. any ideas?
Hi,I would like a piece of advice.I have 3 foreign keys in a table used as primary keys for this table.Is it useful in that case to have just one identity column that wouldbe used as the unique primary key, thus no need to have 3 primary keys?Advantages vs Drabacks ?Regards
I am new to Mobile programming. I am now working on a mobile project. I encounter an issue when I sync the data:
cause I can't modify the schema, so I have to use RDA instead of Merge replication on sql server 2005.
However, There is an identiy column on each table I will pull them down to local mobile database. And I will use those identity columns to connect tables. Even worse, the photo's new name will combine the photoID which is an identity column. There would an issue, if i sync data, the photoID would be same on different local mobile databases. And there would be generate same identity value when users sync data.
How can I avoid those issues? If you have any good ideas, please help me out so that I can meet the project deadline.