Link to home
Start Free TrialLog in
Avatar of Murray Brown
Murray BrownFlag for United Kingdom of Great Britain and Northern Ireland

asked on

VB.net remove all primary keys from SQL Table

Hi

What VB.net code would I use to remove all the primary keys from a SQL table?

Thanks
Avatar of ste5an
ste5an
Flag of Germany image

You would include SQL Server Management Objects in your references and use the IndexCollection to find all indices which are primary keys. Then you may be able to delete them as long as no foreign key relationship exists.

Something like
foreach (Table table in database.Tables)
{
    Index primaryKey = table.Indexes
		.FirstOrDefault(index => index.IndexKeyType == IndexKeyType.DriPrimaryKey);
    if (primaryKey != null)
    {
        primaryKey.Drop();
        table.Alter();
    }
}

Open in new window

.
A given table could have only one primary key, so you don't need to worry about any kind of looping or multiple entries.
hmm, need new glasses. I really read tables..(
Avatar of Murray Brown

ASKER

I use the following code to add the keys. What similar code would I use to remove them
          Dim oSQL As String
            oSQL = "ALTER TABLE " & oTable
            oSQL = oSQL & " ADD CONSTRAINT pk_" & oTable & " PRIMARY KEY ([" & oColumn1 & "], [" & oColumn2 & "])"
            'oSQL = oSQL & " GO"
            Dim cn As New SqlConnection(Globals.ThisAddIn.oRIGHT.lblConnectionString.Text)
            Dim cmd As New SqlCommand(oSQL, cn)
            cn.Open()
            cmd.ExecuteNonQuery()
ASKER CERTIFIED SOLUTION
Avatar of Anthony Perkins
Anthony Perkins
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks