HowTo check Primary Keys in a table

I need to change the primary key of a table in a script in Sybase 11.

Before I change it I need to make sure that it hasn't already been changed. How do I check to see if the primary key has already been changed

If Not Exists (Select 0 IF 'TableName' has primary key of (col1,col2)) Then
    //Perform Change
End If

How would the psuedo Select statement really look?
Who is Participating?
grant300Connect With a Mentor Commented:
The best way to do this is to take a stroll through the system tables.

First, you have to get the object id from the primary key.  You can do this by name using the object_id() function.

Next, you have to determine what columns are in the primary key.  Since you have the column names, e.g. col1 and col2, you can do something like... (see the snippet)  I have not tested the code below but it should be pretty close.

Now that does not tell you anything about the order in which the columns appear in the key,  If you are changing just the order, you have a bigger problem.  It is possible but I am not going to deal with that mess unless you really need it.


          FROM syscolumns
         WHERE name IN ('col1', 'col2')
           AND id = object_id('PK_NAME_HERE')
     ...... blah blah blah ......

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.