[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 588
  • Last Modified:

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?
0
rufassa
Asked:
rufassa
1 Solution
 
grant300Commented:
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.

Regards,
Bill



IF 2 = (SELECT COUNT(*)
          FROM syscolumns
         WHERE name IN ('col1', 'col2')
           AND id = object_id('PK_NAME_HERE')
  BEGIN
     ...... blah blah blah ......
  END

Open in new window

0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now