samesdavis Posted February 20, 2018 at 03:01 PM Report #609414 Posted February 20, 2018 at 03:01 PM 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 Rechousa Posted February 20, 2018 at 03:12 PM Solution Report #609418 Posted February 20, 2018 at 03:12 PM 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, 1 Report Pedro Martins Sharing is Knowledge! http://www.linkedin.com/in/rechousa
samesdavis Posted February 20, 2018 at 04:20 PM Author Report #609421 Posted February 20, 2018 at 04:20 PM Muito obrigado, problema resolvido.
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now