i have two Queries and for that two Queries i had taken two Grid Views
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'
During my page load i need to display the Data in Grid View.
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();
}
is There any alternative rather than taking 2 SQLcommands, 2 SqlDataAdapter, 2 Dataset.....
Could you not just combine those two queries into one?
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')
Keep in mind that you should avoid hard-coding field values like that if at all possible, and use parameters instead.
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);
That block of code is simplified...you could pass in the parameter values in any way that you wanted, and you should probably keep things clean by defining the entire thing as a separate function or stored procedure, so you could pass in whatever value you wanted. I just defined the two parameters in the code for illustration purposes.
Related
I want to get only single row from multiple rows with same projectname from the datatable.(Eg. if we have two rows with same projectname,the datatable should be loaded with the only one row and neglect the other one.).I have been using webservices which has the datatable.
I want to achieve this functionality using linq.
I have pasted my code for datatable.Pls help me with working code.
[WebMethod]
public DataTable Get()
{
int a = 0;
cmd = con.CreateCommand();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = " Select PROJECTNAME,COMPANY,PROJECTSTATUS,STARTEDIN,COMPLETEDIN FROM CMPPROJECT WHERE STATUS ='" + a + "'";
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
dt.TableName = "CMPPROJECT";
sda.Fill(dt);
return dt;
}
}
}
You can create a DataView object which has a method ToTable in which you can pass true to parameter distinct to select distinct rows. But this has no sense to me. I would do this directly in a select query:
DataTable d = new DataTable("CMPPROJECT");
d.Columns.Add("PROJECTNAME");
d.Columns.Add("COMPANY");
d.Rows.Add(1, 1);
d.Rows.Add(1, 1);
d.Rows.Add(2, 2);
d = new DataView(d).ToTable("CMPPROJECT", true, "PROJECTNAME", "COMPANY");
Here is `linq solution:
var select = (from a in d.AsEnumerable()
select new { c1 = a["PROJECTNAME"], c2 = a["COMPANY"] }).Distinct().ToList();
d.Clear();
foreach (var item in select)
d.Rows.Add(item.c1, item.c2);
string date = ddlShowDates.SelectedValue.ToString();
cmd = new SqlCommand("SELECT tbl_Shows.ShowTime FROM tbl_Shows INNER JOIN tbl_MovieTimings ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId WHERE tbl_MovieTimings.Date='" + date + "'", con);
I want to display show time in dropdownlist as per date is selected.
Always use sql-parameters instead of string concatenation to prevent sql-injection.
I guess you have a second DropDownList which should be filled from the first:
DateTime date = DateTime.Parse(ddlShowDates.SelectedValue);
string sql = #"SELECT tbl_Shows.ShowTime
FROM tbl_Shows
INNER JOIN tbl_MovieTimings
ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId
WHERE tbl_MovieTimings.Date=#Date";
using(var con = new SqlConnection("ConnectionString"))
using(var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#Date", SqlDbType.Date).Value = date;
con.Open();
using(var rd = cmd.ExecuteReader())
{
while(rd.Read())
{
TimeSpan time = rd.GetTimeSpan(0);
timeDropDownList.Items.Add(time.ToString());// change format as desired in TimeSpan.ToString
}
}
}
dconnetion = New OdbcConnection(lsconnectionstring)
dconnetion.Open()
mssql = "select cust_id,cust_name,cust_address,cust_contact_no from cust_details where cust_id in (select cust_id from cust_details)"
cmd.Connection = dconnetion
cmd.CommandText = mssql
cmd.CommandType = CommandType.Text
dr = cmd.ExecuteReader
I use this statement to read data from a database using DataReader.
The problem is that when I use DataSet instead of DataReader what will the query is?
Using DataAdapter.Fill() method with the same query.
dconnetion = new OdbcConnection(lsconnectionstring);
//dconnetion.Open()
mssql = "select cust_id,cust_name,cust_address,cust_contact_no from cust_details where cust_id in (select cust_id from cust_details)";
cmd.Connection = dconnetion;
cmd.CommandText = mssql;
cmd.CommandType = CommandType.Text;
using (OdbcDataAdapter da = new OdbcDataAdapter(cmd))
{
DataSet ds = new DataSet();
dconnetion.Open();
da.Fill(ds);
dconnetion.Close();
}
2 questions for everybody.
1) How can I order the years by their value, it crashes when I use DESC?
2) If I populate my list like so:
string strConn = ConfigurationManager.ConnectionStrings["rde_410978ConnectionString"].ToString();
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Distinct Year from MonthlySales DESC"; //DESC DOESNT WORK?
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
How can I make the year selected appear under ddItems.SelectedItem?
WHERE Year = " + ddItems.SelectedItem + "GROUP BY Name ";
That part of another query doesn't work when I populate my list dynamically, any reasons why/ how can I fix it.
Regards.
EDIT:
To make my second question clearer, after debugging its always selecting the top item in the drop down list not the actual selected item?
First, in your sql you are missing "order by"...use this
"Select Distinct Year from MonthlySales order by Year DESC"
Second, you need to make use of the SelectedValue property to get your dropdown's selected value...as below...
WHERE Year = " + ddItems.SelectedValue + " GROUP BY Name";
Having said that, I strongly recommend you to use..."parameterized" sql...Here is an example on how you could enable parameterized sql query...
Give me parameterized SQL, or give me death
Update:
Looks like you are binding your dropdown on every post back...you may try this...
if (!Page.IsPostBack && objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
Ans 1)
cmd.CommandText = "Select Distinct Year from MonthlySales ORDER BY 1 DESC"
You are missing order by. Here it is.
"Select Distinct Year from MonthlySales order by Year DESC";
For your second part you can do this. Please mind the space in " GROUP BY Name"
WHERE Year = " + ddItems.SelectedItem.Text + " GROUP BY Name ";
using (SqlConnection con = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Distinct Year from MonthlySales Order By DESC";
using (DataSet objDs = new DataSet())
{
using (SqlDataAdapter dAdapter = new SqlDataAdapter())
{
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
}
}
}
}
SQL Server procedure can return result sets. I have a table emp(emp__id, emp__name, ...). The procedure below will return a list of employees that matched with the name provided.
CREATE OR REPLACE PROCEDURE get_employee_by_name ( #name VARCHAR(100) )
AS
SELECT emp_id, emp_name
FROM emp
WHERE emp_name = #name;
So in the client code, to get the data I use ADO.NET.
SQLDataAdapter adapter = new SQLDataAdapter("get_employee_by_name", cnString);
SQLDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable("employee");
adapter.Fill(dt);
How can I code equivalently in PL/SQL?
Use a Ref cursor for the Stored Procedure:
http://www.oradev.com/ref_cursor.jsp
For the client part use the Oracle Data Provider. You can download it from Oracle and the syntax is similar to the SQLDataAdapter. Something like this:
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = new OracleCommand("get_employee_by_name", Connection);
OracleParameter prm = da.SelectCommand.Parameters.Add("pName", OracleDbType.VarChar2);
prm.Direction = ParameterDirection.Input;
prm.Value = "MyName";
prm = da.SelectCommand.Parameters.Add("pResult", OracleDbType.RefCursor);
prm.Direction = ParameterDirection.Output;
DataTable dt = new DataTable();
da.Fill(dt);