SQL RowNumber Where条件

时间:2013-05-11 08:21:09

标签: sql sql-server

如何向此添加WHERE条件;

sqlcmd = new SqlCommand("SELECT A.* from Experiment A INNER JOIN 
             (SELECT ROW_NUMBER() OVER(ORDER BY AutoID ASC) AS 'RN', "+
             "*FROM Experiment) B  ON A.AutoID= B.AutoID AND B.RN between 
             11 and 21 ", con);

这是完整的代码;

protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
      // sqlcmd = new SqlCommand("Select *From Experiment", con);
     sqlcmd = new SqlCommand("SELECT A.* from Experiment A INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY AutoID ASC) AS 'RN', "+
       "*FROM Experiment) B  ON A.AutoID= B.AutoID AND B.RN between 11 and 21 ", con);


        adapter = new SqlDataAdapter(sqlcmd);
        DataSet ds = new DataSet();
        con.Open();
        adapter.Fill(ds, "Experiment");
        Repeater1.DataSource = ds;
        Repeater1.DataBind();
     }   
}

2 个答案:

答案 0 :(得分:0)

sqlcmd = new SqlCommand("SELECT A.* from Experiment A INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY AutoID ASC) AS 'RN', "+ "*FROM Experiment) B ON A.AutoID= B.AutoID AND B.RN between 11 and 21 " + "WHERE ......", con);

答案 1 :(得分:0)

我已将您的查询抽象为字符串变量(注意,以@开头的字符串可以携带多行)

string sqlQuery = @"
    SELECT A.* 
    FROM Experiment A 
    INNER JOIN (
        SELECT ROW_NUMBER() OVER(ORDER BY AutoID ASC) AS 'RN', *
        FROM Experiment) B ON A.AutoID = B.AutoID AND B.RN BETWEEN 11 AND 21"

sqlcmd = new SqlCommand(sqlQuery, con);

要添加其中,只需将其附加到字符串

即可
sqlQuery += " WHERE B.RN = @RowNumberFilter AND A.AutoID = @AutoIDFilter";

我过滤到只显示与行号过滤器和AutoId过滤器匹配的行

但是你需要告诉sql命令参数的值是什么。

假设

int rowNumberFilter = "15";
int autoIDFilter = "101";

你有两个选择

// options 1
// explicitly add the parameter with the type then set the value
sqlcmd.Parameters.Add("@RowNumberFilter", SqlDbType.Int);
sqlcmd.Parameters["@RowNumberFilter"].Value = customerID;

// option 2
// implicitly add the parameter using AddWithValue(..) to convert the type
sqlcmd.Parameters.AddWithValue("@AutoIDFilter", autoIDFilter);

使用参数而不是将值直接汇总到查询中的好习惯。

例如这是不好的

sqlQuery += " WHERE B.RN = " + rowNumberFilter.ToString() + " AND A.AutoID = " + autoIDFilter.ToString();

使用using语句也是一种好习惯; SqlConnection,SqlCommand和我认为SqlDataAdapter是一次性的,所以你应该用using语句包装它。

using (SqlConnection conn = new SqlConnection(...))
{
   ...
}