Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a View from SQL Server 2008 in C# & Asp.net

I have a C#/ASP.net project has included a database that I have developed that includes a nice and convenient View that would be handy to use.

I have the SQL connection setup to a SQL Server 2008 DB I created. It seems as though it is connecting fine, but I don't understand how to actually use the View that I created without hard coding the query into the program (been told this is bad sometimes?).

This is my connection I setup:

    SqlConnection conn = null;
    conn = new SqlConnection("Data Source=raven\\sqlexpress;Initial Catalog=ucs;Integrated Security=True;Pooling=False");
    conn.Open(); 
    SqlCommand command = new SqlCommand(query, conn);

Basically, I need some code to query using this View. I can see the View and look at the results that would be obtained, but not access it in the program! The view is named "UserView". Help is much appreciated!

like image 303
ImGreg Avatar asked Jul 06 '11 18:07

ImGreg


1 Answers

You could use something like the following. But it's usually considered evil to put hardcoded SQL commands into .Net code. It's much better and safer to use stored procedures instead.

This should get you started. You can modify it to use stored procedures by

  1. changing the command.CommandType to indicate it's a stored proc call
  2. And adding the proper parameters to the command that your SP needs.
  3. Change command.CommandText to the name of your SP, thus eliminating the hardcoded SQL.

sample code below:

using (SqlConnection connection = new SqlConnection("Data Source=raven\\sqlexpress;Initial Catalog=ucs;Integrated Security=True;Pooling=False"))
{
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "SELECT * from your_view WHERE your_where_clause";

        connection.Open();
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                // process result
                reader.GetInt32(0); // get first column from view, assume it's a 32-bit int
                reader.GetString(1); // get second column from view, assume it's a string
                // etc.
            }
        }
    }
}
like image 68
dcp Avatar answered Nov 06 '22 22:11

dcp