i want to select two queries from 1 stored procedure....my following query is correct? and how to call this in 2 gridview
create procedure tablename
#id varchar(50)
as
select a.id,
isnull(a.advance,0) as advance,
isnull(b.submitted_amt,0) as submitted
into #temp1
from
(select id,SUM(Amount)as advance
from table1 where type='Travel' group by id) a
full join
(select id,SUM(Amount)as submitted_amt
from table2 group by categeoryid) b
on a.id=b.id
select id,
advance,
submitted,
advance-submitted as balance_return
from #temp1
select categeoryid,advance,submitted,advance-submitted as balance_return from #temp1 id=#id
Please use this sample:
private void GetMultiSelect()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "AllDetail";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter sqlParam = cmd.Parameters.Add("#Id", SqlDbType.Int, 4);
sqlParam.Value = 1;
//dataset object to get all select statement results
DataSet ds = new DataSet();
//sql dataadoptor to fill dataset
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
//here all select statements are fill in dataset object
adp.Fill(ds);
//now u can fetch each and every select statement by providing table index in dataset
foreach (DataTable dt in ds.Tables)
{
//select statement result in dt..
}
//or instead of loop u can specify the index
GridView1.DataSource= ds.Tables[1]; // first select statement result
GridView1.DataBind();
GridView2.DataSource = ds.Tables[0]; // second select statement result
GridView2.DataBind();
}
}
}
}
Please go to this link for details
Related
I have a dropdown and I want to check the selected value first before I run my SQL command so here is my logic: if the selected value of the dropdown is not 'ALL' then I want to run this sql statement:
select distinct Location
from myTable
where PROGRAM = '"+program+'"
else if selected value of the dropdown is set to 'ALL' then I want to run this SQL command instead:
select distinct Location
from myTable
Here is my my code which works fine but not the way I want it to work. How can I modify the SQL command so I can check the condition that I mentioned above? Thanks
protected void BindServiceList(DropDownList ddlService)
{
DropDownList ddl = (DropDownList)GV_MJJ.HeaderRow.FindControl("ddlProgram");
string program = ddl.SelectedValue;
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["myConn"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("select distinct LOCATION" +
" from myTable where PROGRAM = '" + program + "' ");
cmd.Connection = con;
con.Open();
ddlService.DataSource = cmd.ExecuteReader();
ddlService.DataTextField = "LOCATION";
ddlService.DataValueField = "LOCATION";
ddlService.DataBind();
con.Close();
ddlService.Items.FindByValue(ViewState["Filter_Serv"].ToString())
.Selected = true;
}
Don't change your SQL command instead create different SQL command's text based on the condition. Also you should use SqlParameter instead of string concatenation. Your code is prone to SQL injection. Consider enclosing your connection and command object in using statement as that will ensure resource disposal at the end of block.
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlDataAdapter sda = new SqlDataAdapter();
using (SqlCommand cmd = new SqlCommand())
{
if (program.Equals("All", StringComparison.InvariantCultureIgnoreCase))
{
cmd.CommandText = "select distinct LOCATION from myTable";
}
else
{
cmd.CommandText = "select distinct LOCATION from myTable WHERE PROGRAM = #program";
cmd.Parameters.AddWithValue("#program", program);
}
cmd.Connection = con;
con.Open();
ddlService.DataSource = cmd.ExecuteReader();
ddlService.DataTextField = "LOCATION";
ddlService.DataValueField = "LOCATION";
ddlService.DataBind();
con.Close(); // can be left out because of `using` statement
ddlService.Items.FindByValue(ViewState["Filter_Serv"].ToString())
.Selected = true;
}
}
Do this:
protected void BindServiceList(DropDownList ddlService)
{
DropDownList ddl = (DropDownList)GV_MJJ.HeaderRow.FindControl("ddlProgram");
string program = ddl.SelectedValue;
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["myConn"].ConnectionString;
using (var con = new SqlConnection(strConnString) )
using (var cmd = new SqlCommand("select distinct LOCATION from myTable where PROGRAM LIKE #Program", con) )
{
//guessing at column type/length here
cmd.Parameters.Add("#Program", SqlDbType.NVarChar, 20).Value = program;
con.Open();
ddlService.DataSource = cmd.ExecuteReader();
ddlService.DataTextField = "LOCATION";
ddlService.DataValueField = "LOCATION";
ddlService.DataBind();
}
ddlService.Items.FindByValue(ViewState["Filter_Serv"].ToString())
.Selected = true;
}
Notice that I fixed your sql injection vulnerability! Also notice that I changed the = to a LIKE. Then you can set the value property for the All item in the ddlProgram control to: %. (See the AppendDataBoundItems property if you need help getting that working with a databound ddl). Using that wildcard with the LIKE operator will result in the query returning all locations.
Firstly Parameterize your query.
Since there are already solutions using c#. I will propose a SQL solution.
You could do a Case in your WHERE CLause by passing a parameter that suggests if the dropdown value is ALL.
Something like:
SELECT DISTINCT Location
FROM myTable
WHERE (
CASE
WHEN #IsAllSelected = 0
THEN PROGRAM
WHEN #IsAllSelected = 1
THEN 1
END
) = (
CASE
WHEN #IsAllSelected = 0
THEN #Your_program_value
WHEN #IsAllSelected = 1
THEN 1
END
)
I am trying to create an attendance table to record down the activities the students have participated. The code below is triggered when a new activity is created. When a new activity is created, I want to insert all the student record into attendance table and mark the default attend attribute as false. (the attend attribute is to mark attendance, sets as 0)
The problem is that the attendance table cannot be populated. The code will stop proceeding at the line: numofRecordsAffected = command.ExecuteNonQuery();
I am trying to get the all the sigstudentid(s) from the Student table. I do not know if the usage of foreach() is recommended in this case, but any help will be appreciated.
I need a solution!
public int InsertAttendance(int num)
{
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand();
SqlConnection connect = new SqlConnection();
DataSet dataset = new DataSet();
String sqlText = "SELECT * FROM Student";
connect.ConnectionString = "Data Source=TECKISTTLE; Initial Catalog=Assignment; Integrated Security=True";
command.Connection = connect;
command.CommandText = sqlText;
int numofRecordsAffected = 0;
adapter.SelectCommand = command;
connect.Open();
adapter.Fill(dataset, "StudentData");
sqlText = "";
foreach (DataRow item in dataset.Tables["StudentData"].Rows)
{
sqlText += " INSERT INTO Attendance(SIGStudentID, ActivityId, Attendance) VALUES(#SIGStudentID,#ActivityId,#Attendance); ";
command.Parameters.Clear();
command.Parameters.Add("#SIGStudentID", SqlDbType.Int);
command.Parameters["#SIGStudentID"].Value = Convert.ToInt32(item["SIGStudentID"]);
command.Parameters.Add("#ActivityId", SqlDbType.Int);
command.Parameters["#ActivityId"].Value = num;
command.Parameters.Add("#Attendance", SqlDbType.Bit);
command.Parameters["#Attendance"].Value = 0;
}
numofRecordsAffected = command.ExecuteNonQuery();
connect.Close();
return numofRecordsAffected;
}
As you put the code numofRecordsAffected = command.ExecuteNonQuery(); out side your foreach.
It just execute one time. As this code is actual statement to INSERT data in to the table, it will INSERT only one ROW the last one.
Just try to put your code
numofRecordsAffected = command.ExecuteNonQuery();
inside the foreach block. Then it will INSERT each row.
public int InsertAttendance(int num)
{
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand();
SqlConnection connect = new SqlConnection();
DataSet dataset = new DataSet();
String sqlText = "SELECT * FROM Student";
connect.ConnectionString = "Data Source=TECKISTTLE; Initial Catalog=Assignment; Integrated Security=True";
command.Connection = connect;
command.CommandText = sqlText;
int numofRecordsAffected = 0;
adapter.SelectCommand = command;
connect.Open();
adapter.Fill(dataset, "StudentData");
sqlText = "";
numofRecordsAffected = 0;
sqlText = "INSERT INTO Attendance(SIGStudentID, ActivityId, Attendance) VALUES(#SIGStudentID,#ActivityId,#Attendance); ";
command.CommandText = sqlText;
foreach (DataRow item in dataset.Tables["StudentData"].Rows)
{
command.Parameters.Clear();
command.Parameters.AddWithValue("#SIGStudentID", Convert.ToInt32(item["SIGStudentID"]);
command.Parameters.AddWithValue("#ActivityId", num);
command.Parameters.AddWithValue("#Attendance", 0);
numofRecordsAffected += command.ExecuteNonQuery();
}
connect.Close();
return numofRecordsAffected;
}
You're probably over complicating it a bit by using a loop and could do something like this instead:
"INSERT INTO Attendance(SIGStudentID, ActivityId, Attendance) select SIGStudentID, " + num + " as ActivityId, 0 as Attendance from Student;"
Reference:
insert one column data from a table into other table, but the other column data will be specified dynamically
Insert all values of a table into another table in SQL
I try to add custom paging and when I login through username and password, an error occurs.
Also I show document only his/her documents like when abc is login then abc only able to view her documents, but when I add custom paging it show me error UserID is not supplied and I also share sp code
Code is
protected void BindRepeater()
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["mydms"].
ConnectionString.ToString());
SqlCommand cmd = new SqlCommand("sphrdoc2", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
PagedDataSource pgitems = new PagedDataSource();
DataView dv = new DataView(dt);
In this line
adp.Fill(dt);
error occurs
Procedure or function 'sphrdoc2' expects parameter '#UserID', which was not supplied.
sp is
ALTER procedure [dbo].[sphrdoc2]
#UserID int
as
Select
dbo.DocumentInfo.DocID as DocumentID,
dbo.DocumentInfo.DocName as DocumentName,
dbo.DocType.DocType as Document,
dbo.Department.DepType as Department,
dbo.DocumentInfo.Uploadfile as FileUploaded,
dbo.ApproveType.ApproveType AS Status
FROM
dbo.DocumentInfo
inner JOIN dbo.DocType ON dbo.DocumentInfo.DocTypeID=dbo.DocType.DocTypeID
inner JOIN dbo.Department ON dbo.DocumentInfo.DepID=dbo.Department.DepID
left join dbo.ApproveType on dbo.DocumentInfo.ApproveID=dbo.ApproveType.ApproveID
where UserID=#UserID
Any one tell me where I done mistake in repeater code?
You need to pass parameters for your stored procedure .
SqlCommand cmd = new SqlCommand("sphrdoc2", con);
cmd.Parameters.AddWithValue("#UserID","YourUserID");
if (con.State == ConnectionState.Closed)
{
con.Open();
}
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
Can anyone tell me how to get the value from SELECT query from a table
protected void Button_Click(object sender, EventArgs e)
{
string select_qry = "SELECT ID, USER, FILE, DATE, LASTUSED from FILE_INFO where USER = '" + user + "'"; // ID is primary key
SqlCommand cmd = new SqlCommand(select_qry);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = conn1;
conn1.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
I have different USERS I want to get ID of user if user is different say 'Sheena' has ID value from 1-10 but if user is 'Sara' and she is having ID from 11-20 so I want to get specially ID of particular user how do I get ID from select query can any one know then please help me out :)
if the ID will always be first in the select statement you can call this:
VB.NET
var dt = GetData(cmd);
dt.Rows.Item(0).Item("ID")
C#.NET
var dt = GetData(cmd);
dt.Rows[0]["ID"];
I am not getting you quite well. but
Sample data
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("userName", typeof(string));
dt.Rows.Add(1, "Sheena");
dt.Rows.Add(2, "Meena");
dt.Rows.Add(2, "Teena");
To get id of first row.
if (dt.Rows.Count > 0)
{
// return id in first row.
int id = (int)dt.Rows[0]["id"];
}
DataTable Select method
if (dt.Rows.Count > 0)
{
DataRow[] dr = dt.Select("userName = 'Meena'");
if (dr.Length > 0)
{
int id2 = (int)dr[0]["id"];
}
}
There are other methods too but these are quickly I can write.
I think you could do that in your query like
Select case id >= 11 and id <= 20 then 'specially id' end as ID ......
Because 'user' is a parameter so you can know the id range when you creating the query.
So that , there is no need any logic in your source code , just fetch data as #Mark said..
I Had Drop down list and I want to fill it with data from database through stored procedure
and it had it,s value when specific query string I had two query string.
as
private void LoadWithCategory()
{
if (Request.QueryString["Category_Id"] != null)
{
using (SqlConnection Con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("GetProducFamilyTP", Con);
Com.CommandType = CommandType.StoredProcedure;
Com.Parameters.Add(Parameter.NewInt("#Category_Id", Request.QueryString["Category_Id"]));
SqlDataReader DR = Com.ExecuteReader();
if (DR.Read())
{
DDLProductFamily.DataSource = DR;
DDLProductFamily.DataTextField = DR["Name"].ToString();
DDLProductFamily.DataValueField = DR["ProductCategory_Id"].ToString();
DDLProductFamily.DataBind();
}
DR.Close();
}
}
}
ALTER Proc GetProducFamilyTP
(
#Category_Id Int
)
AS
Select Distinct Categories.Category_Id ,ProductCategory.Name ,
ProductCategory.ProductCategory_Id
From Category_ProductCategory
Inner Join Categories
On
Category_ProductCategory.Category_Id=Categories.Category_Id
Inner Join ProductCategory
On
Category_ProductCategory.ProductCategory_Id=ProductCategory.ProductCategory_Id
Where
Categories.Category_Id =#Category_Id
but this error occurred
DataBinding: 'System.Data.Common.DataRecordInternal' does not contain a property with the name '4Door'.
The error was in ddl list when I removed it it worked well it had value=0