给SQL 文本命令中的参数传值

SqlCommand对象的CommandType属性值有三种类型:Text、StoredProcedure和TableDirect,我们都知道,在存储过程中使用参数是非常常见的,因而我们都知道当CommandType值为StoredProcedure时怎么给存储过程参数传值,但是要知道SQL 文本命令中也是可以带参数的,那怎么给他们传值呢?其实两者是一样的,看下边例子:

string Country = "UK";
string City = "London";

using (SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;User ID=sa;Password=sa"))
{
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandTimeout = 60;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "Select count(*) From [Customers] Where Country=@Country And City=@City";
    cmd.Parameters.Add(new SqlParameter("@Country",Country));
    cmd.Parameters.Add(new SqlParameter("@City",City));
    conn.Open();

    Response.Write(cmd.ExecuteScalar());
}

在SQL 事件探查器中看到的结果为:

exec sp_executesql N'Select count(*) From [Customers] Where Country=@Country And City=@City', N'@Country nvarchar(2),@City nvarchar(6)', @Country = N'UK', @City = N'London'


评论: 0 | 引用: 0 | 查看次数: 6790
发表评论
登录后再发表评论!