Jump to content

Recuperar chave primária por GetSchema


Go to solution Solved by Rechousa,

Recommended Posts

Posted

Boa tarde,

 

Preciso recuperar qual é o nome do campo da chave primária de uma tabela usando GetSchema.

Estou usando este código em C# .  A base de dados é SQL Server.

 

Nesse método abaixo eu passo como parâmetro o nome da tabela. 

 

        public string BuscaChave(string mTabela)
        {
            //Cria a conexão
            using (SqlConnection sqlConnection = CriarConexao())
            {
                try
                {

                    //Abre a conexão
                    sqlConnection.Open();
                    DataTable dataTable = sqlConnection.GetSchema("Indexes", new[] { null, null, mTabela });
                    string mChave = string.Empty;
                    foreach (DataRow linha in dataTable.Rows)
                    {
                        mChave = linha.ItemArray[3].ToString();
                        break;
                    }
                    return mChave;

                }
                catch (Exception ex)
                {
                    //retorna mensagem de erro
                    throw new Exception(ex.Message);
                }
                finally
                {
                    //Fecha a conexão
                    sqlConnection.Close();
                }

            }
        }
  • Solution
Posted

Viva,

Se por GetSchema não for um requisito, aqui vai uma solução:

SELECT COLUMN_NAME
	FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
	WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
	AND TABLE_NAME = 'table_name' AND TABLE_SCHEMA = 'schema_name'

Espero ter ajudado,

  • Vote 1

Pedro Martins

Sharing is Knowledge!

http://www.linkedin.com/in/rechousa

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.