Most of the tables in my database are implemented with IDENTITY columns as the primary key.
When an INSERT from my application is attempted, sometimes I get an error returned stating that insert
cannot be done because of duplicate key value. If I try the INSERT again, sometimes it works(??). Of course,
DBCC CHECKIDENT resets the identity value if trying the INSERT again doesn't work. Then sometime a little later, the problem happens again.
Is there anything I can do other than placing into my application code the execution of dbcc checkident
anytime I want to do an insert to prevent the error? By the way, DBCC CHECKDB revealed no problems.
I have a table to store int primary keys. Where the value nextID is the value to use.I need to get the value and update it (nextID + 1) before the next person gets it.I thought using tran would work but it doesn't stop a select.How do I get a value (lock the table for the update), update the table (preventing any selects until done) and release the table.
BEGIN TRAN UPDATE TableIds SET NextId = NextId + 1 WHERE TableName = 'Users'
WAITFOR DELAY '00:00:20'
SELECT NextId FROM TableIds WHERE TableName = 'Users'
COMMIT TRAN
I really want to do this in the reverse order but it doesn't work. But if I do this and have another query to just do a select:
SELECT NextId FROM TableIds WHERE TableName = 'Users'
This query never returns. Doesn't the COMMIT TRAN release the lock on the table?
Can a Primary Key column also be a Identity column? The reason I am asking this question is because I have created a table and each time I insert data into the Address Table I am also inserting the AddressID, how do I get the Primary Key (AddressID column) to self generate ID values.
If I right click on a primary key in SQL Server management studion, I can set the identity specification for a primary keyId so that it is indexible. I do this by setting the properties for "Is Identity", "Identity Increment", and "Identity Seed". This is wonderful, but I have been asked to perform this using a script instead of the SQL server GUI/Sql Server management studio. Is this possible? Does anyone know how to do this? If so, can you show me how? Ralph
I am building a database for a new project. I am not a DBA or a database designer so please bear with me on this question. My boss believes that the only time to use an identity column is when we cannot determine a unique primary key. On tables where we can determine a unique primary key identify fields are a waste of reasources. For instance, one of the tables that I need to create is a customer table. Since all of our customers have unique customer numbers my boss believes that in this case an identity column is useless. I don't have enough experience to determine if he is correct or not. Can someone please explain the pro's and con's of using identity fields to me. Thanks
I orginally had my project ID specified as an Int and the properties set as identity specification that would automatically fill in the ID field however I have now changed it as the ID needs to be specified by the user but now when i update a project the ID isnt seen as the identity so whatever i do affects other records not just the one i select. it is now defined as an nvarchar but i dont know how to set that as the identity so that each record can be edited seperately, can someone please help this is really urgent!! Im using visual web developer express with sql server, please please help!
I want to crete temporary table with this coammnd "CREATE TABLE Temp (ID int, name varchar(50))". I would like to know which command is used for setting primary key and identity on ID field. Thankyou in advance.
I have some code in my ASP.NET page which uses a SQL 2000 Database that was created before creating the ASP Page. The problem I'm having is using an insert statement such as the following example from the DATAGRID example on the Matrix Product. I want the option to create new rows but my Primary Key doesn't allow Nulls and when I hard code a number in the first field of my table for my ID...it's not automatically generated. I've looked through this forum but I'm having some problems understanding what others have done with Identity or GUID's...etc....:
Sub AddNew_Click(Sender As Object, E As EventArgs)
' add a new row to the end of the data, and set editing mode 'on'
CheckIsEditing("")
If Not isEditing = True Then
' set the flag so we know to do an insert at Update time AddingNew = True
' add new row to the end of the dataset after binding
' first get the data Dim myConnection As New SqlConnection(ConnectionString) Dim myCommand As New SqlDataAdapter(SelectCommand, myConnection)
Dim ds As New DataSet() myCommand.Fill(ds)
' add a new blank row to the end of the data Dim rowValues As Object() = {"", "", ""} ds.Tables(0).Rows.Add(rowValues)
' figure out the EditItemIndex, last record on last page Dim recordCount As Integer = ds.Tables(0).Rows.Count
Can anyone explain the Difference between Primary Key and Identity Column in MSSQL Server 6.5. Please give me any example if possible. Thanks for Help!!!!
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 want to use the Identity field (increment 1,1) as a primary key andhave a unique constraint on my other field which is of type char.I am worried that related data in other tables may lose referntialintegrity if records in the ID table get messed up and need to bere-entered.Can you please advice on best way to do this. I definitely need anumeric id field because it makes the joins and queries so muchfaster.
We are converting a legacy visual foxpro system to use a SQL back-end.A number of (existing DBF) tables currently have a zero-filled primarykey eg. '000255' which is just an auto-incrementing key - but alwaysstored as a char field with leading zeros.For backward compatibility we are considering retaining this primarykey and using an identity field to auto-generate the next value, thenconvert the new identity value into the new primary key. So ifidentity is 256 then the key field will be assigned '000256'.Now the problem with this is that the primary key must be non-null andunique so must be given a value in the INSERT statement. But, theidentity value isn't available (I presume) until after the INSERTstatement has executed.Is this a "don't go there" kind of problem?ThanksAndrew GrandisonSA Department of HealthAdelaide, South Australia
Hi! a) PROBLEM 1: I have set up my main database like this (of course I'm showing an abbreviation): company - int (identity)name - nchar I have several companies stored in the previous table. Now I have another table with messages: company - int (related with the company of the previous table)messageID - int (identity)contents - nchar company and messageID are the main key of this table. I want to set the messageID column to change automatically. Since I declared it as identity it is working fine, but I was looking to start it on 0 on every new company: Company messageID0 00 10 21 0 <- Here the company changed, so the messageID resets1 11 21 32 0 <- Again2 1 Any suggestions? b) PROBLEM 2:I have my database stored locally on my computer. When I finished working with the database it has a lot of data for testing. I want to upload the database to my hosting provider or to my customer's. But the identity columns keep incrementing since the last value of my tests, so it's kind of annoying to see values as: 1250, 223, etc. when I expect to see 0,1, 2 and so on. Also, for receipts this is a very important issue. How can I reset the identity fields? Thank you very much for your attention and help. CT
HiI've a tabel with two columns as identity fields (one as primary key), but I read in SQL 2000 documentation that it is permitted only one column as identity, it's true?The second field has to be autoincrement so I supposed to use identity field for it...Now the true problem, supposing that I can use two identity fields...I'd like to reset the second identity when the year change... In other words, I've to manage some spedition which are identified with XXX/year, where XXX is a number.Coming from Oracle, I supposed to use a trigger on insert which reset the sequence when the year changa, but in MS??Tnx...
I am experiencing a problem with the identitynumber field in SQL vs the autonumber field in MS Access 97. When I open the Member Contact form(Access), it generates the autonumber on the form, which is then visible on the form itself. That form has several pulldown/pop-up boxes which are used to select criteria. One of the form buttons, the Add Comments button, once pushed, it brings up a Comments form. This Comments form references the autonumber that was generated on the Member Contact form in order to open itslef. The information is then entered into the Comments form and the form is then saved. All the selected information is saved to that record upon the saving of that form.
Now, my problem has to do with getting the identity number(SQL) to generate on the Member Contact form and also allowing the Comment form to open by referencing that generated identitynumber just like Access does without having to save the record first then coming back and adding a comment later.
Do anyone know if it is possible? If so, does anyone have any suggestions on how to generate a identitynumber before saving the entire record?
I have a table that I need to add an identity field to. I created a field in the table as an INT and added values to all of the existing records. When I try to change it to an IDENTITY field I continually get an error saying 'Invalid cursor state' . The help function tells me that this is caused by not having enough space in the transaction log but I don't understand this b/c the trans log is configured to expand as needed. Anyone know how I can do this?
Hello -- Following normal practice, I have an autoincrementing identity column designated as primary key in my table. I have two other columns that should also contain unique values per record, but the Identity option is greyed out (in Management Studio) for all columns other than the primary key. I'm enforcing this programmatically (in my C# code) at this point, but I'd like to back that up with a constraint in the database itself. Any help is appreciated. Eric
I have the following issue - my database consists of tables with one ID field as primary key. for each INSERT the 'next' value from this ID field is extracted from a table called TableList. - this works perfectly fine, as long as I insert one record at a time: but now I would like to run a command such as INSERT INTO dest (name) SELECT name FROM src i.e. without being able to specify the ID value. Has anybody implemented this (i would prefer not to use identity columns or use cursors), possible with triggers?
SELECT T.TABLE_NAME,C.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLES T JOIN INFORMATION_SCHEMA.COLUMNS C ON T.TABLE_NAME = C.TABLE_NAME WHERE OBJECTPROPERTY(OBJECT_ID(T.TABLE_NAME), 'TableHasIdentity') = 0 AND T.TABLE_TYPE = 'BASE TABLE' AND OBJECTPROPERTY(OBJECT_ID(C.COLUMN_NAME),'IsPrimary Key') = 1 ORDER BY T.TABLE_NAME,C.COLUMN_NAME
This is giving me bogus results...
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE OBJECTPROPERTY(OBJECT_ID(COLUMN_NAME),'IsPrimaryKe y') = 1
I have PK's all over the place. What gives? Too many cocktails with lunch?
We are developing a batabase which is meant for financial domain,so it will import data from different source system.. and data from our data base will be further passed to other applications.
In contex of our system integration with other data sources ,whether is it a good idea to have a auto integer primary key a or to implement some logic to generate primary key?
Can some one guide us to some pratical data base design case studies?or some best practices.?
We will be using SQL Compact Edition in our application. We are doing some tests to make sure that SQL Compact is suitable for our requirments.
Our problem is with Primary keys and how to maintain data integrity since we will have 100+ clients inserting, updating, and synchronizing with SQL Server.
Can we control Identity range?
Shall we use UniqueIdentifires insted of int?
How can we detect errors at the client side? (For example, if two clients are trying to synchronize 2 columns with the same primary key value)
I am relativley new to SQL and have a question about identity fields.
I am creating a script to run everynight to insert records into a support table in a database. one of the fields is a identity field that is updated everytime a record is added locally or over the web.
Some records that are added into the database locally by users do not get added into theis support table, but so those new people entered in can use the website a entry must be added to this support table.
I am working on a script to take the records that where added by users and automatically put them in every night using a basic schedueled job.
The identy number is updated everynight in a table that collects all the important identiy numbers. I would like to use this table to alter the seed value and then increment by one every time a new record is added. This is my only sticking point so far.
Hi, I am trying to replicate our application database (SQL server 2005) using transactional replication to another server. What I did was, took a backup of the live database and restored in backup server with same name. Then did a transactional replication. Issue is we have few tables having Identity columns defined as primary keys and 'Not for Replication' option of these tables is 'NO'. But once published, this becomes 'Yes' and also replication failed showing an error as
Explicit value must be specified for identity column in table <table name> either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column.
In the table article, for the parameter 'Action If name is in use', I have selected 'Drop the existing object and create a new one' (Also tried another option 'Delete Data'). How to resolve these issues.
I have a table used by multiple applications. One column is an Identify field and is also used as a Primary key. What isare the best practices to use get the identity value returned after an INSERT made by my code.. I'm worried that if someone does an INSERT into the same table a "zillionth" of a second later than I did, that I could get their Identity value.
We are facing the following issue, several machines/users that are executing very often a command similar to :
INSERT INTO TableName (FieldOne,FieldTwo) VALUES ('ValueOne','ValueTwo'); SELECT SCOPE_IDENTITY() AS Table_ID;
Where TableName has a primary key defined as identity(1,1).and that Table_ID is being used as reference in others tables
These queries are executed using different dababase users and among several diffrent apps..The Problem is that we are detecting lost block of "Table_ID's" as the other tables shows the InsertedID as a reference, but the TableName table lacks of this ID record. In other words, the INSERT seems to work, the SCOPE_Identity returns an InsertedID, and the other tables are populated using this number. However, when we query the TableName table the mentioned record does not exist. We are profiling the server and we're sure that there are no DELETE statement on the TableName table. This seems to be happening when the are either deadlocks or blocked processes. Whenever the deadlocks and locks disappear/solved, everything works as expected.why the Scope_Identity returns the Inserted ID if the INSERT action had failed.
I'm just getting my feet wet with how encryption works in SQL 2005. With regards to the encryption of primary / foreign keys, I'm not entirely clear on the best approach. Below are three examples of typical table structures I currently have:
The Customers and Orders tables use identity values as their primary keys. From what I can tell, CustomerID in the Customers table cannot be encrypted and OrderID in the Orders table cannot be encrypted because they are identity values. In these cases, would it be safer (in terms of security) to create a separate, meaningless identity key column in the Customers table and then remove the identity attribute from CustomerID so I can encrypt CustomerID?
Similarily in the OrderDetails table, OrderID and ItemNumber form a composite key. These values are important in that I don't want them to be tampered with. Am I better off creating a separate identity key column which becomes the table's primary key ... then encrypt both the OrderID and ItemNumber columns in this table?