-2

如何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 之间
             11 和 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();
     }   
}
4

2 回答 2

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);
于 2013-05-11T08:23:53.443 回答
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);

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

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

我正在过滤以仅显示与行号过滤器和 AutoId 过滤器匹配的行

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

假设

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

你有 2 个选项

// 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(...))
{
   ...
}
于 2013-05-11T08:45:04.757 回答