Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server






SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





Using An Identity Field As Primary Key


I want to use the Identity field (increment 1,1) as a primary key and
have a unique constraint on my other field which is of type char.
I am worried that related data in other tables may lose referntial
integrity if records in the ID table get messed up and need to be
re-entered.
Can you please advice on best way to do this. I definitely need a
numeric id field because it makes the joins and queries so much
faster.




View Complete Forum Thread with Replies
Sponsored Links:

Related Messages:
Identity Primary Field In Merge Replication
Hello I currently have a merge replication set up with 4 subscribers. A primary field for one of my tables is set to a integer indetity.

 

What Ive noticed is that depending on which database I enter data into, the indentity field (primary key) is set within a certain range I.e

 

On Server 1 - Values start from 1 then 2,3,4 etc etc

 

Server 2 - 24001, 24002, 24003 etc etc

 

Server 3 - 46001, 46002, 46003 etc etc

 

Server 4 - 68001, 68002, 68003

 

My question is what happens when these ranges eventually conflict? Do they automatically gain a different range such as 142 001, 142 002 etc etc?

 

Ive tried looking in SQL Help, and a quick search here, Im just after some confirmation before I implement this to my app.

 

cheers

View Replies !   View Related
Insert Row In Table With Identity Field, And Get New Identity Back
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?

 

View Replies !   View Related
Identity And Primary Key
I confuse about Identity and primary key, what is the different between them. One table can have no primary key. Right? Thanks.

View Replies !   View Related
Primary Key To Identity
Hi,

Is it true that having a primary key (PK) in a column that the data might change is a very high cost and we have to avoid it?

Is the answer is to replace the PK by ‘Identity’?

If so, how would I maintain the relationship with other tables? As the PK is a multiple columns, some of them are foreign keys (FK).

Your ideas, answers will be appreciated.
Thank you in advance.

Harith

View Replies !   View Related
Primary Key And Identity
Can someone tell me the difference between making a column primary key column vs. making it identity column?

 

thanks

View Replies !   View Related
Setting Identity, Primary Key
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.

View Replies !   View Related
URGENT!!! Primary Key As Identity
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!

View Replies !   View Related
Primary Key Vs Identity Column
What is the different between Primary key and Identity Column? and when should I them?
(Im just a beginner with databases...)

View Replies !   View Related
Help Needed With Primary Key And Identity
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

If recordCount > 1 Then

recordCount -= 1
DataGrid1.CurrentPageIndex = recordCount DataGrid1.PageSize
DataGrid1.EditItemIndex = recordCount Mod DataGrid1.PageSize

End If

' databind
DataGrid1.DataSource = ds
DataGrid1.DataBind()

End If


End Sub

View Replies !   View Related
Using Identity To Generate A Primary Key
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

View Replies !   View Related
Primary Key VS Identity Column
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!!!!

View Replies !   View Related
How To Change Integer Field To Identity Field.
I have an integer column(not null) in a table. how can i change that to identity column through query analyzer, through a script, b'cos i have to apply this to number of databases.
I tried this, but got an error:

ALTER TABLE table_name
alter column company_id int IDENTITY

ERROR:
Incorrect syntax near the keyword 'IDENTITY'.

any help is welcome.

View Replies !   View Related
Converting An Integer Field Into An Identity Field
I have a table with an integer field (contains test values like 2, 7,8,9,12,..) that I want to convert to an Identity field. How can this be done in t-sql?

TIA,

 

Barkingdog

 

 

 

View Replies !   View Related
Last GASP On &&"Insert Row In Table With Identity Field, And Get New Identity Back &&" ?
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?

 

TIA,

 

Barkingdog

View Replies !   View Related
What Is Diffecence Indexes, Primary Key And Identity.
What is diffecence indexes, primary key and identity.

View Replies !   View Related
Designating An Identity Column When You Already Have Primary Key
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

View Replies !   View Related
How To Insert Primary Keys Without Using Identity
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?

thanks for your time,

Andre

View Replies !   View Related
Trying To Find Non Identity Primary Keys
This ain't working

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?

View Replies !   View Related
Identity Fields As Primary Key In Server 7.0
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.

HELP!

View Replies !   View Related
Identity Column Primary Key Vs Custom Key
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.?

View Replies !   View Related
Primary Key, Identity, Integrity Constraints
Hi,

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)

 

We will use Merge replication.

 

Thank you

View Replies !   View Related
Primary/Foreign/Identity Keys && Encryption
Hi all!

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:

== Customers table ==
CustomerID (PK, int, Identity)
CustomerName (varchar)

== Orders table ==
OrderID (PK, int, Identity)
CustomerID (int, foreign key)
CreditCardNumber (varchar)

== OrderDetails table (1 to Many) ==
OrderID (PK/FK, int)
ItemNumber  (PK, int)
ItemDescription (varchar)

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?

Any ideas are appreciated.

Thank you,
Ben

View Replies !   View Related
How To Find All Tables That Have An Identity Column As A Primary Key
 How do i find all the tables that have an Identity Column as a primary key in a database. Thanks.

View Replies !   View Related
Inserting Into SQL 7.0 With An Identity Column As The Primary Key Problems
Hi I'm using Visual Web Developer Express 2005 and I'm connecting to a SQL 7.0 database.  The table I'm connecting to is a table where I store help desk issues that I've encountered.  Since I could have tons of help desk issues with multiple instances of the same user, same issue I decided to go with a column called "ID" as the primary key, I was also thinking of using an automatic time stamp but I'd rather use the "autonumber".  "ID"s property is set to Identity.  To select,update,insert and delete I just use the automatic generate statements VWD makes for you.  Select, Delete and update work fine but the insert gives me this error.
ERROR [23000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot
insert explicit value for identity column in table 'HelpDesk'
when IDENTITY_INSERT is set to OFF. Even though it says I'm inserting something into the identity column I am not.  That box isn't available when I'm inserting a new HelpDesk issue.
I've tried many things I've seen on forums such as:  putting the Identity_insert ON statement in my insert statement, not putting the "ID" column in the insert statement(which works but then it will insert the data into the wrong columns).  Here is the insert statement generated by VWD

INSERT INTO [HelpDesk] ([ID], [Username], [Issue], [Resolution]) VALUES (?, ?, ?, ?)

oh, also I don't think I want to use a GUID because that seems like it will be to large for what I'm doing.
Any suggestions would be appreciated

View Replies !   View Related
Change In Pk Field Into An Identity Field - How?
Ok, simply problem. I have a table that has an in primary key field. I want to (need to) set this up as identity, through a script.

Is it right that there is no (working) alter table statement for this? After trying for two hours I finally just started to look on how Enterprise Manager handles this. And - EM basically...

...creates the new table,
...sets IDENTITY_INSERT to ON,
...copies the data over (select *, insert)
...deletes the old table and renames the new one.

Frankly, this is not really nice.

Anyone a better idea?

View Replies !   View Related
Change Field To Identity Field
I have a table named PERSON and a field named PERSON_ID. How can I set this field to Autonumber? I know I have to use the IDENTITY command, but when I view this field in "design" view, all the IDENTITY options are grayed out.

How can I set this field with the IDENTITY properties?

Thanks

View Replies !   View Related
How To Set The Identity Specification For A Primary Key Using A Script, Instead Of SQL Server Management Studio?
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

View Replies !   View Related
Primary Key Field
Hi,

I want to find out the primary key field name of the table using system table information i.e. sysobjects, syscolumns etc.
I tried to find it out but it seems to be very complicated.
Could anybody help me in this regards?

Thanks in advance.
Prasanna.

View Replies !   View Related
Bit Field As Primary Key
Hey guys.
I just wanted to ask you a question? we are having a field declared
as BIT and we want that field to be unique..We are not able to declare
as a primary key..Is there anyway to declare as unique from the database
point of view?..please help us out in this issue and i'd appreciate that.

Andrew.

View Replies !   View Related
New Primary Key Field
Does anyone has an idea on creating a new field in a table with more then say 10000 rows already in that table, and making that new field as primary key field. None of the fields in that table are unique.

View Replies !   View Related
How To Get A New Value For A Primary Key Field
Hello,
 
I have an app that is connected to SQL 2005 express edition.
In the DB there is a table that has an auto incremental primary key
What I want is, I want to get a new value for that auto incremental field before sending the new record's date to the DB to be stored. So I can display the new record's ID in my app's interface
 
So is there something in SQL server like SEQUENCE in oracle.
 
 
Thanks in advance.
 

View Replies !   View Related
How To Get The Primary Key From The Field Of The Row I've Just Inserted
I need to insert a row of data and return the value of the primary key id of the row.
I thought that something like this would work


int Key = (int)command.ExecuteScalar();


where command is SqlCommand object.

It doesn't work, maybe I've misunderstood the usage of ExecuteScalar.

View Replies !   View Related
Multi-field Primary Key
I have a table (table1) that has a bunch of fields....[field1][field2][field3][field4][field5]None of these fields are unique, but if I combine them, then they areunique.I know there is a way to make multi-field primary keys, but when I tryI get an that field1 is not unique, which I already know,How can I make a multi-field primary key?thanks

View Replies !   View Related
How To Auto Increment A Primary ID Field?
I was just wondering on a very simple database table with lets say a primary key set to columb ID and another columb lets say products, can you make the primary key automaticly increment its self whenever a new entry has been put in?For instance say I have this table set up with ID Being the primary KEY, Columb 1 = ID( INT ), Columb 2 = Products ( VarChar(50) ), and have the fields ID = 1, and products = my product.....and if a user inserts a new record say from a gridview or some sort of data entry the second ID Feild will automaticly be  2 and the products gets updated per user input.......I'm very sorry but I'm having a hard time putting this into words for some reason..umm basicly user adds something into the products feild and the ID field automaticly increments one number higher from the last one?ThanksAdam.

View Replies !   View Related
Duplicate Entry In A Primary Key Field
Hi everybody couldn't get through with saving my data on the table with two primary keys...

my table structure is this

pubidintUnchecked (primary key)
pubchar(1)Unchecked
publchar(1)Unchecked
pubcodechar(2)Unchecked (primary key)

a sample data is here

pubid pub publ pubcode

1 a b ab
1 b b bb
2 a b ab
2 b b bb


when i save this table modifying the pubid and pubcode as primary keys the following error displays...

Unable to create index 'PK_PUBS3'.
CREATE UNIQUE INDEX terminated because a duplicate key was found for index ID 1. Most significant primary key is '51'.
Could not create constraint. See previous errors.
The statement has been terminated.


what i understand is that on the primary key duplicates are not allowed how could i allow it?

thanks

View Replies !   View Related
Automating Incrementation In Primary Key ID Field
I'm really puzzled with this. I am new to using MS SQL and need help with the primary key. When I was using Access, I would open the database table and just enter values for the various columns, each time a new column was begun, the computer would insert a unique number there. OK, so now I am using visual studio to work on a SQL database. I created a new table and the first field I specified was "ID", I then chose it as the primary key. For default value, I tried both auto number and auto increment. These don't seem to work, as when I type values into fields and try to move to the next row, having left the ID field blank, I get an error which reads "String or Binary data may be truncated". What is going on, what do I need to do so the field automatically populates with an ID number... Some research sort of led me to the concept of a "trigger" to do this. Is this the approach. I was able to r-click on the table and I saw an option for "create trigger" or "new trigger"... How do I learn to do this, is there a generic trigger to do an auto increment of a primary key ID field?

View Replies !   View Related
Insert Values In Primary Key Field
Hi,

Does anyone know how should I create a table in order that I can insert values(numbers)  in the primary key field, using insert statements. I also would like to know if there are any differences between SQL 2k and SQL 2k5.

Thanks in advance for any reply.

View Replies !   View Related
Sql Identity Field
Hello friends,
I had created a web application and uploaded the application. Now the problem is with the DB. I had created the DB on  the server (using script). But the fields that have identity field yes is not been set  Now how I can set the fields identity field to yes. Fields are already there. Only I want to set there identity field to yes.Let me know how this can be done.
Thanks & RegardsGirish Nehte

View Replies !   View Related
Re-set Identity Field
Hi:
I created a small SQL Express database/ASP.net/C# application and in the learning process.   Before I implement it I would like to re-set autonumber / identity field back to 1.  Also, I need to start with the blank database.  I am not sure how to approach that?
Can you assist?
Thanks 
 
 

View Replies !   View Related
&<&<identity Field&>&>
hi friends,i have an identity column in my table.(e.x : id )and it's identity increment is 1.when i insert a row the id field is 1, and in next record the field is 2.....now , i delete second record(id=2)and now when i insert a record again , the id column is 3.i want to record be 2 instead 3.plz help me.thanks

View Replies !   View Related
Identity Field
Please, How can I get the value of the identity field of the register that I was including in the data base. I am using a stored procedure in SQLSERVER in a asp .net application and I need to show that for the user, it´s like the number of the reclamation.

View Replies !   View Related
Identity Field
Folks

I am inserting some values into a table with the following stmt

Insert into table(number,name) values ('12','name')

In the table I have one more identity column ID. I know that I cannot insert a value in that column and the value is automatically increased once I insert a record. After this insert statment, I need to get the value
of the ID (the most recent one) in the next select statement.

ie Select @@identity from table (any condition????)

How do I get the most recent ID value? Actually I m inserting the records in a loop and the ID is increased for every insert.


Thanks for the help,

View Replies !   View Related
Identity Field
Greetings !

Having an unusual problem - have created several (20) tables in a database.
All of these tables have an identity field in them (defined as FIELDNAME int IDENTITY(1,1) NOT NULL ). In most of the tables this works as expected, but in 2, so far, when I do the first load (an insert based on a different database) the identity fields are all zero.
Have recreated the tables, changed the field name and location, etc.
Anyone have any clues ?

TIA

Eric

View Replies !   View Related
Identity Field
Dear Fellow Administrators,

We are experiencing an identity problem on a table with 3.7 millions rows of data in the table. The identity field is not auto numbering any more and are wondering if anyone has a suggestion on how to get the auto number field working again without doing a bcp and restoring the table back to the database from bcp. Any suggestions?

Thanks in Advance,
Daimon

View Replies !   View Related
Identity Field
I need to update an identity field that I have on a table. How can
I go about doing this?

Thanks!
Toni

View Replies !   View Related
Bcp With IDENTITY Field
If my table has an IDENTITY field, say, the table schema is:
CREATE TABLE BBB(
id int NOT NULL IDENTITY(1,1),
name varchar(20),
job varchar(40))
My data file, which does not carry the IDENTITY field
and its field terminator. The data file looks like this:

debbie cao,programmer
John Doe,engineer
Mary Smith,consultant

I tried to use a format file to bulk copy data from the
data file to the table. Never had any luck.
On the other hand, if I put a comma before the name field,
say, the data file looks like the following:

,debbie cao,programmer
,John Doe,engineer
,Mary Smith,consultant

then, bcp works fine.
But, my data file is automatically generated. It does not
suppose to have the leading comma. Without the leading comma,
I have no idea how may I make bcp work. The SQLBOL says it
can be done. Does anybody have an example to show me?
Please help, thanks!

View Replies !   View Related
Identity Field Fix
I inherited a system with a SQL 2000 DB.  We discovered an identity field named barcode with some values that are incorrect.  About 1000 of the records contain a barcode field with 13 digits, not forteen as required.  This field is a standalone field only used on an ID card.  I would like to select those 1000 records and update the barcode field to 14 digits.  Is there an easy way to do this?    Thx

View Replies !   View Related
Identity Field
Hello...

New to SQL and have the following situation....

Example of table (currently)
PayID (Primary Key) PaymentNumber (Identity Field)
John 1
Tim 2
Chris 3
John (same as John above) 4
Jack 5
Steve 6

Would like to see it work this way
PayID (Primary Key) PaymentNumber (Identity Field)
John 1
John (same as John above) 2
Tim 1
Chris 1
Jack 1
Steve 1

Can the identity column be setup to start the counter over depending on value of PayeeID...If another Jack was added then the Payment Number would be 2 for Jack since there is already a record with value 1....

Hope this makes sense...

Thanks

View Replies !   View Related

Copyright © 2005-08 www.BigResource.com, All rights reserved