I've tried searching StackOverflow but the query returns a lot of unrelated results and I did spend time looking elsewhere before posting. I am writing an app in C# / ASP.NET and would like to pull just the Full Names and id from the database of employees who work in my office. I can successfully query the database with:
SELECT * FROM name;
But if I try anything else at all I get an error. Here's what I'd like to use as my statement:
SELECT id, first_name, last_name AS 'Full Name' FROM name;
Here's my C# calling code (note: I inserted a generic connection string name for this post):
MainWindow.xaml.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
string connetionString = null;
SqlConnection sqlCnn;
SqlCommand sqlCmd;
string sql = null;
connetionString = @"Database=aspnetdb;user id=;password=;data source=localhost";
sql = "SELECT * FROM name";
sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
MessageBox.Show(sqlReader.GetValue(0) + " - " + sqlReader.GetValue(1) + " - " + sqlReader.GetValue(2));
}
sqlReader.Close();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
You need to use this syntax.
SELECT id, first_name, last_name AS [Full Name] FROM name;
Single quotes are used to denote strings. Square brackets should be used for field names that contain spaces.