Skip to content

Instantly share code, notes, and snippets.

@amarodeabreu
Created February 23, 2021 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amarodeabreu/3b0d033d6dab80c1267dac06c5e6fb0c to your computer and use it in GitHub Desktop.
Save amarodeabreu/3b0d033d6dab80c1267dac06c5e6fb0c to your computer and use it in GitHub Desktop.
/// <summary>
/// Get primary key columns for selected table
/// </summary>
private void GetKeyColumns()
{
// New key column class
_tableKeyColumnsArrayList = new List<TableKeyColumns>();
// Get db name from settings file
var database = Properties.Settings.Default.Database;
// Select primary ket columns from sql for selected table
var sql = "USE [" + database + "] SELECT COLUMN_NAME As KeyColumns FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE with (nolock) WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1 AND TABLE_NAME = '" + TableName + "' AND TABLE_SCHEMA = 'dbo'";
using (var connection = new SqlConnection(ConnectionString))
{
var command = new SqlCommand(sql, connection);
connection.Open();
var reader = command.ExecuteReader();
try
{
while (reader.Read())
{
// Add primary key columns to class list for later usage
_tableKeyColumnsArray = new TableKeyColumns
{
ColumnName = reader["KeyColumns"].ToString(),
};
_tableKeyColumnsArrayList.Add(_tableKeyColumnsArray);
}
}
catch (Exception ex)
{
reader.Close();
// Show alert on error - no message boxes, using popups
var alertInfo = new AlertInfo("Error", ex.Message);
var control = new AlertControl { FormLocation = AlertFormLocation.BottomRight };
control.Show(ParentForm, alertInfo);
}
reader.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment