Monday, December 28, 2020

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

 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.
            }
        }
    }
}

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...