working with primary key column

  • 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 ??

  • Hi,

    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.

    Regards

    Gurpreet Sethi

  • 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)

    etc.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply