Click here to monitor SSC
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in
Home       Members    Calendar    Who's On

Add to briefcase

working with primary key column Expand / Collapse
Posted Wednesday, May 27, 2009 10:43 PM


Group: General Forum Members
Last Login: Sunday, August 9, 2009 11:55 PM
Points: 24, Visits: 76
if a table is having 2 columns col1 and col2. if col1 is primary key.
col1 col2
1 "aa"
2 "bb"
3 "cc"
4 "dd"

if i want to run some update query on this table as
update table tab-name
set col1 = col1 + 1

it will cause primary key constraint violation error.
So is it ok, we can do the same work by disabling the primary key constraint ??
Post #724790
Posted Thursday, May 28, 2009 1:08 AM
SSC Journeyman

SSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC Journeyman

Group: General Forum Members
Last Login: Thursday, November 10, 2016 2:46 PM
Points: 94, Visits: 469

Please run below steps on your test database.

create table test (col1 int primary key, col2 varchar(10) )

insert into test values(1,'col1')
insert into test values(2,'col2')
insert into test values(3,'col3')
insert into test values(4,'col4')

select * from test

update test set col1=col1+1

select * from test

You will see it will update the column without any problem...:)

Now the reason:

We know SQL server works in Auto Commit mode means what ever query we write on Query Window automatically got comitted. Now this will only happen by the time it will complete its execution. So Once execution will be done all rows will be succesfully updated by new values.

Please let me know if you are facing any problem. Please share your script as well if its there.


Gurpreet Sethi
Post #724839
Posted Monday, June 1, 2009 7:01 AM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Thursday, June 11, 2009 2:35 AM
Points: 50, Visits: 14
Updating the Primary Key (1) to (1+1=2) would create two records with the same Primary Key (2). This will not work, and should not be attempted.

A Primary Key constraint requires the column to be unique; and constrains the user's actions to keep this rule.

Perhaps you are trying to update the Foreign Keys (the related records)?

Table 1
ColourID | Colour
1 | red
2 | blue
3 | green
4 | yellow

Table 2
ItemID | Item | ColourID
1 |Red Car |1
2 |Red Brick |1
3 |Red Pencil|1
4 |Blue things|2

If ColourID in table 1 was updated from 1 to 2, the PKEY 2 would mean both red and blue, and the related items in table 2 would appear as both red and blue (1,red car,code for blue & code for red)

Post #726615
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse