Passing parameters to SQL saves you from having to build a dynamic SQL string.
Building dynamic SQL statements is a HUGE security risk because people can inject their own SQL code into your application, possibly executing undesirable commands against your data.
There are some good samples of possible SQL Injection attacks at:
SQL Injection Attacks by Example
There are two ways of passing parameters to SQL statements. One is to use Stored Procedures like you mentioned. The other is to use parameterized queries (which is actually what I prefer).
A parameterized query is actually quite easy in .NET:
using(SqlConnection conn = new SqlConnection(connString))
{
SqlCommand command =
new SqlCommand("SELECT * FROM Users WHERE Username = @Username", conn);
command.Parameters.Add(new SqlParameter("@Username", "Justin Niessner"));
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable dt = new DataTable();
adapter.Fill(dt);
}
In that example, the parameter was @Username
and we used the Parameters
collection of the SqlCommand
object to pass in the value.