0

我有两个查询,对于这两个查询,我采取了两个网格视图

select course_name , start_date, end_date, timings, fee, branch_code from coursesprovided    where start_date>=Getdate() and branch_code='Ameerpet'

select course_name , start_date, end_date, timings, fee, branch_code from coursesprovided where start_date>=Getdate() and branch_code='Hi-Tech City'

在我的页面加载期间,我需要在网格视图中显示数据。

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(local); Initial Catalog=gateway; User   Id=sa; Password=wilshire@rnd; Integrated Security=false";


            //Assigning Query
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
cmd.CommandText = "select course_name , start_date, end_date, timings, fee, branch_code from coursesprovided where start_date>=Getdate() and branch_code='Ameerpet'";

cmd.CommandText = "select course_name , start_date, end_date, timings, fee, branch_code  from coursesprovided where start_date>=Getdate() and branch_code='Ameerpet'";

            cmd.CommandType = CommandType.Text;


            //Execute the COmmand
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds);
            gvap.DataSource = ds;
            gvap.DataBind();
}

除了采用2 个 SQLcommands、2 个 SqlDataAdapter、2 个数据集之外,还有其他选择吗.....

4

1 回答 1

0

你能不能把这两个查询合二为一?

 SELECT [course_name], [start_date], [end_date], [timings], [fee], [branch_code] FROM [coursesprovided] WHERE [start_date] > = GETDATE() AND ([branch_code] ='Ameerpet' OR [branch_code] = 'Hi-Tech City')

请记住,如果可能的话,您应该避免对字段值进行硬编码,而是使用参数。

 String branchCode1 = "Ameerpet";
 String branchCode2 = "H-Tech City";

 cmd.CommandText = "SELECT [course_name], [start_date], [end_date], [timings], [fee], [branch_code] FROM [coursesprovided] WHERE [start_date] > = GETDATE() AND ([branch_code] = @BranchCode1 OR [branch_code] = @BranchCode2)";

 da.SelectCommand.Parameters.AddWithValue("BranchCode1", branchCode1);
 da.SelectCommand.Parameters.AddWithValue("BranchCode2", branchCode2);

该代码块被简化......您可以以任何您想要的方式传递参数值,并且您可能应该通过将整个事物定义为单独的函数或存储过程来保持事物清洁,因此您可以传递任何值你自找的。出于说明目的,我只是在代码中定义了两个参数。

于 2013-10-29T21:06:14.707 回答