user489041
user489041

Reputation: 28312

How to get the primary key of a table in sql server 2008

I have the following code which should be able to get the primary key in a table

public List<string> GetPrimaryKeysForTable(string tableName)
    {
        List<String> retVal = new List<string>();
        SqlCommand command = connector.GetCommand("sp_pkeys");
        command.CommandType = System.Data.CommandType.StoredProcedure;
        command.Parameters.AddWithValue("@table_name", typeof(SqlChars)).Value = tableName;
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            retVal.Add(reader[3].ToString());
        }
        return retVal;
    }

I have a table called Users in my database. When I pass Users in as my parameter, the reader returns no results. Any idea why this might be failing to return my primary keys?

Upvotes: 2

Views: 2141

Answers (6)

Rich Turner
Rich Turner

Reputation: 11014

Question: Does your table have any keys defined?

I have run the slightly modified code below against severa tables in a test DB of my own and it works as expected:

static class Program
{
    static void Main(string[] args)
    {
        var connStr = new SqlConnectionStringBuilder
        {
            DataSource = "localhost",
            InitialCatalog = "RichTest",
            IntegratedSecurity = true
        };

        using (var conn = new SqlConnection(connStr.ToString()))
        {
            conn.Open();

            var parents = GetPrimaryKeysForTable(conn, "People");

            Console.WriteLine("Parent Keys:");
            foreach (var p in parents)
            {
                Console.WriteLine("  {0}", p);
            }
        }
    }

    static IList<string> GetPrimaryKeysForTable(SqlConnection conn, string tableName)
    {
        if (conn == null) throw new ArgumentNullException("Value is null", "conn");
        if (string.IsNullOrWhiteSpace(tableName)) throw new ArgumentNullException("Value is null or emtpy", "tableName");

        List<String> retVal = new List<string>();
        using (var command = new SqlCommand
        {
            Connection = conn,
            CommandText = "sp_pkeys",
            CommandType = CommandType.StoredProcedure
        })
        {
            command.Parameters.AddWithValue("@table_name", typeof(SqlChars)).Value = tableName;
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                retVal.Add(reader["COLUMN_NAME"].ToString());
            }
        }
        return retVal;
    }

}

Upvotes: 0

Matt F
Matt F

Reputation: 595

The stored procedure 'sp_pkeys' takes three parameters:

command.Parameters.Add("@table_name", SqlDbType.NVarChar).Value = tableName;
command.Parameters.Add("@table_owner", SqlDbType.NVarChar).Value = tableOwner;
command.Parameters.Add("@table_qualifier", SqlDbType.NVarChar).Value = tableQualifier;

It works with just @table_name but could try passing all three to see if it makes a difference.

Upvotes: 0

Elias Hossain
Elias Hossain

Reputation: 4469

You can simply use as below, would you please try it out:

command.Parameters.AddWithValue("@table_name", ("dbo." + tableName));

Upvotes: 0

Phil Klein
Phil Klein

Reputation: 7514

It looks like you have an issue with your usage of .AddWithValue() which may be causing your problem. See the fix below:

public List<string> GetPrimaryKeysForTable(string tableName)
{
    List<string> retVal = new List<string>();
    SqlCommand command = connector.GetCommand("sp_pkeys");
    command.CommandType = System.Data.CommandType.StoredProcedure;
    command.Parameters.AddWithValue("@table_name", tableName);
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        retVal.Add(reader[3].ToString());
    }
    return retVal;
}

In your example you are attempting to add the @table_name as a Type rather than a string.

Upvotes: 1

MusiGenesis
MusiGenesis

Reputation: 75396

Try this instead:

command.Parameters.Add("@table_name", SqlDbType.NVarChar).Value = tableName;

Upvotes: 1

Matt Felzani
Matt Felzani

Reputation: 795

Any chance it needs to be qualified with the schema? Something like:

command.Parameters.AddWithValue("@table_name", typeof(SqlChars)).Value = "dbo." + tableName;

or:

command.Parameters.AddWithValue("@schema", "dbo");

Or is there some parm you need to add to tell it the database inside the server?

Upvotes: 0

Related Questions