Reading multiple rows of data using sqldatareader - asp.net

I've the below sql statement as follows:
SELECT * FROM ViewSectorInvestments WHERE AccountNumber = #AccountNumber
Fields in ViewSectorInvestments:
AccountNumber
SectorName
AmountInvested
I'm trying to compute the AmountInvested in each sector against the total investments.
So the formula will be: AmountInvested/TotalInvestments * 100
my code is as follows:
string DMConnectionString = ConfigurationManager.ConnectionStrings["DMConnectionString"].ConnectionString;
SqlConnection DMConnection = new SqlConnection(DMConnectionString);
DMConnection.ConnectionString = DMConnectionString;
string DMCommandText = "SELECT Name,RiskProfile,AccountNumber,TotalInvestments FROM ViewClientDetails WHERE AccountNumber = #AccountNumber; SELECT * FROM ViewSectorInvestments WHERE AccountNumber = #AccountNumber ;SELECT * FROM ViewStockTypeInvestments WHERE AccountNumber = #AccountNumber ";
SqlCommand DMCommand = new SqlCommand(DMCommandText, DMConnection);
DMCommand.Parameters.AddWithValue("#AccountNumber", lb_AcctNum.Text);
DMConnection.Open();
SqlDataReader DMReader = DMCommand.ExecuteReader();
ArrayList SectorArray = new ArrayList();
ArrayList StockTypeArray = new ArrayList();
while (DMReader.Read())
{
CustName.Text = DMReader["Name"].ToString();
lb_Risk.Text = DMReader["RiskProfile"].ToString();
T_Investment.Text = DMReader.GetDecimal(DMReader.GetOrdinal("TotalInvestments")).ToString("N2");
Client_RiskProfile.Text = DMReader["RiskProfile"].ToString();
//encounter error when i add the datas into arraylist.
//System.IndexOutOfRangeException: SectorName
SectorArray.Add(DMReader.GetOrdinal("SectorName").ToString());
StockTypeArray.Add(DMReader.GetOrdinal("BlueChipName").ToString());
foreach( Object objReader in SectorArray){
//compute the percentage of amount invested in each sector
//check if the percentage is more than 25%
//if it is more than 25% lbMsg (an label) shows the name of the sector.
}
}
DMReader.Close();
DMConnection.Close();
}
When i test out the sql statement :
SELECT * FROM ViewSectorInvestments WHERE AccountNumber = #AccountNumber
The result i got is :
AccountNumber SectorName AmountInvested
1001 Commerce 97230.00000
1001 Construction 389350.00000
1001 Finance 222830.00000
1001 Hotel 14910.00000
1001 Loans 105070.00000
1001 Manufacturing 1232210.00000
1001 Mining/Quarrying 32700.00000
I encountered System.IndexOutOfRangeException: SectorName.
What's wrong with my code?
Please advice me. Thanks in advance.

string DMCommandText = "SELECT Name,RiskProfile,AccountNumber,TotalInvestments FROM ViewClientDetails WHERE AccountNumber = #AccountNumber; SELECT * FROM ViewSectorInvestments WHERE AccountNumber = #AccountNumber ;SELECT * FROM ViewStockTypeInvestments WHERE AccountNumber = #AccountNumber ";
This CommandText contains multiple queries. Only the results from the last SELECT statement will be returned to the SqlDataReader.
SectorArray.Add(DMReader.GetOrdinal("SectorName").ToString());
You are trying to access the column ordinal of a field called "SectorName" in your SqlDataReader. The problem causing your exception is probably that the column doesn't exist, but it's hard to say since you are using SELECT * in your CommandText.

Related

While loop in stored procedure in sql returns only one row to grid view in asp.net

Using while loop in stored procedure works correctly in SQL server but returns only first row to asp.net grid view.
My stored procedure
create procedure [dbo].[DoorDetails]
#emp varchar(16),
#fromdate datetime,
#todate datetime,
#cdate datetime =#fromdate
as
while #cdate<= #todate
Begin
select convert(varchar,(CONVERT(date,#cdate,103)),103) as Date, Empname, min(TransactionDateTime) as EntryTime ,max(TransactionDateTime) as ExitTime,
(DateDIFF (MINUTE,min(TransactionDateTime), max(TransactionDateTime)))/60 as Hours,
(DateDIFF (MINUTE,min(TransactionDateTime), max(TransactionDateTime)))%60 as minutes from
ceptEmpTxn where EmpName = #emp and cast(TransactionDateTime as Date)=cast(#cdate as date) group by empname
SET #cdate = DATEADD(dd,1,#cdate)
end
GO
Result in SQL
-------------------------------------------------------------------------------------------------------------
|Date| |Empname| |EntryTime| |ExitTime| |Hours| minutes|
|14/09/2016| |PRAVEEN KUMAR| |2016-09-14 09:28:13.000||2016-09-14 18:42:14.000 9 14
------------------------------------------------------------------------------------------------------------
|Date| |Empname| |EntryTime| |ExitTime| |Hours| minutes|
|15/09/2016| |PRAVEEN KUMAR| |2016-09-15 09:27:13.000||2016-09-15 17:16:46.000 7 49
-------------------------------------------------------------------------------------------------------------
|Date| |Empname| |EntryTime| |ExitTime| |Hours| minutes|
|16/09/2016| |PRAVEEN KUMAR| |2016-09-16 09:30:33.000||2016-09-16 19:03:14.000 9 33
Headers are repeating each time in sql
Result in Webpage (using Grid view)
------------------------------------------------------------------------
Date| Empname| EntryTime| ExitTime| Hours| minutes|
15/09/2016| PRAVEEN KUMAR| 15-09-2016 09:27:07| 15-09-2016 17:16:46| 7| 49|
My function in asp.net
public DataTable tottime(string empname, DateTime fromdate, DateTime todate)
{
System.Data.SqlClient.SqlConnection myConn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["ceptConnectionString"].ConnectionString.ToString());
DataTable myDt = new DataTable();
System.Data.SqlClient.SqlCommand myCmd = new System.Data.SqlClient.SqlCommand();
myCmd.CommandType = System.Data.CommandType.StoredProcedure;
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
myCmd.CommandText = "DoorDetails";
myCmd.Parameters.AddWithValue("#emp", empname);
myCmd.Parameters.AddWithValue("#fromdate", fromdate);
myCmd.Parameters.AddWithValue("#todate", todate);
da.SelectCommand = myCmd;
try
{
myCmd.Connection = myConn;
da.Fill(myDt);
return myDt;
}
catch (Exception ex)
{
throw;
}
finally
{
myDt = null;
da.Dispose();
myCmd.Dispose();
myConn.Close();
myConn.Dispose();
}
}
How to return all the values from stored procedure also how to have table header only once followed by all the rows.
Possibly you may have to create a table variable and store the result set there and again fetch that result set at the end. Try this.
P.S Please change the data types of table variable (#t) columns accordingly. So that there will not be any troubles.
create procedure [dbo].[DoorDetails]
#emp varchar(16),
#fromdate datetime,
#todate datetime,
#cdate datetime =#fromdate
as
while #cdate<= #todate
Begin
DECLARE #T TABLE
(
[Date] Date
,Empname VARCHAR(200)
,EntryTime DATETIME
,ExitTime DATETIME
,[Hours] INT
,[minutes] INT
)
INSERT INTO #T
select convert(varchar,(CONVERT(date,#cdate,103)),103) as Date
, Empname, min(TransactionDateTime) as EntryTime
,max(TransactionDateTime) as ExitTime
,(DateDIFF (MINUTE,min(TransactionDateTime), max(TransactionDateTime)))/60 as Hours
,(DateDIFF (MINUTE,min(TransactionDateTime), max(TransactionDateTime)))%60 as minutes
from
ceptEmpTxn where EmpName = #emp and cast(TransactionDateTime as Date)=cast(#cdate as date) group by empname
SET #cdate = DATEADD(dd,1,#cdate)
end
SELECT * FROM #T
GO

Select Values in From SQLServer & Show in The Labels in ASP

i want to Select Values ex(Date,Time....)from SQLServer on the PageLoad & shows Them in The Many Labels. i try this code but in all labels shows the Time . i want to show All Values not one value in all labels . Please help me .
string strquery = "select Time,Date,SeatPrice,EventName from Event_SingleReservation";
SqlConnection connection2 = DBConnection.getConnection();
connection2.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection2;
cmd2.CommandText = strquery;
string eventname = cmd2.ExecuteScalar().ToString();
lbl1_EventName.Text = eventname;
string eventdate = cmd2.ExecuteScalar().ToString();
lbl2_EventDate.Text = eventdate;
string eventtime = cmd2.ExecuteScalar().ToString();
lbl3_EventTime.Text = eventtime;
string seatprice = cmd2.ExecuteScalar().ToString();
lbl_seatpriceshow.Text = seatprice;
The ExecuteScalar() selects only one value from the first column - i.e. using it against select Time,Date,SeatPrice,EventName from Event_SingleReservation will return only Time which is the first column.
To select all values you should use ExecuteReader()
SqlDataReader reader = cmd2.ExecuteReader();
if (reader.Read())
{
lbl1_EventName.Text = reader[0];
lbl3_EventDate.Text = reader[1];
...
}
See What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

Database value in label asp.net c#

I am trying to get value from database to be display in label. First i have to get the value of the dropdownlist and retrieved from database based on it. After that, I need to get the titlePromo column into my Label.
Currently i have the code out but i am not sure if it is the right one. There is no error but it displayed the membershipType column instead of the titlePromo.
ID titlePromo membershipType defaults
-- ---------- -------------- ------
1 Promo 1 Membership Promotion Y
2 Promo 2 Membership Renewal Y
3 Promo 3 Membership Grad Y
4 Promo 4 Membership Promotion N
5 Promo 5 Membership Promotion N
6 Promo 6 Membership Grad N
My codes that i have done so far:
string strConnectionString = ConfigurationManager.ConnectionStrings["FYPDB"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText2 = "select * FROM FYPDB.dbo.Promotions where membershipType = '%' + #membership + '%' AND defaults = 'Y'";
string ddlmembership = ((DropDownList)dvInsertPromotion.FindControl("ddlAddMembershiplist")).SelectedItem.ToString();
cmd.Parameters.Add("#membership", SqlDbType.NVarChar);
cmd.Parameters["#membership"].Value = ddlmembership;
DataSet da2 = dal.retrieveTitle(ddlmembership);
SqlCommand cmd2 = new SqlCommand(strCommandText2, myConnect);
((Label)pnlDefaultPopup.FindControl("Label13")).Visible = true;
((Label)pnlDefaultPopup.FindControl("Label13")).Text = da2.Tables[0].Rows[0]["titlePromo"].ToString();
html:
.cs
public DataSet retrieveTitle(String membership)
{
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("#membership", SqlDbType.NVarChar),
};
parameters[0].Value = membership;
DataSet ds = new DataSet();
ds = commons.ExecuteDataSet("Select * FROM Promotions WHERE (membershipType = '" + membership + "') AND defaults = 'Y' ");
return ds;
}
Before giving you my suggestion I would like to make some remarks to your existing code:
you should select only the titlePromo in your query, as you only need one field, and not the entire row (therefore you wouldn't need a dataset in the first place)
the naming of your function is not according to its scope, at it does not retrieve the title, but an entire entry in the promotions table.
in this structure "membershipType = '%' + #membership + '%'" the syntax is not correct. The wildcards are used together with the "like" keyword
Bellow, you can find my code sample of how would I implement it if I were you:
static void Main(string[] args)
{
using (SqlConnection PubsConn = new SqlConnection(yourConnectionString))
{
//code to retrieve membership
var membership = "Membership Promotion";
var title = retrieveTitle(PubsConn, membership);
//code to set up label
}
}
public static string retrieveTitle(SqlConnection conn, String membership)
{
conn.Open();
var title = string.Empty;
string strCommandText = "select top 1 titlePromo FROM Promotions where membershipType = #membership AND defaults = 'Y'";
SqlCommand commmand = new SqlCommand(strCommandText, conn);
commmand.Parameters.AddWithValue("#membership", membership);
try
{
using (SqlDataReader reader = commmand.ExecuteReader())
{
if (reader != null && reader.Read())
{
title = Convert.ToString(reader["titlePromo"]);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error while retrieving table: " + ex.Message);
}
conn.Close();
return title;
}
If you want to use wildcards and 'like', you can do it like this:
string strCommandText = "select top 1 titlePromo FROM membershipTest where membershipType like #membership AND defaults = 'Y'";
SqlCommand commmand = new SqlCommand(strCommandText, conn);
commmand.Parameters.AddWithValue("#membership", "%" + membership + "%");

Need to insert a data row multiple times in the database

I have two data tables in sql. I need to insert data feom one table to another. My first data table Table1 contain data column Code,Model,Num,Qty and second table Table2 also contain the same. But I need to insert the data from table1 to table2 multiple times. If Qty in Table1 is 4 then, insert the data of
Table1 for 4 times according to the quantity.
protected void Button15_Click3(object sender, EventArgs e)
{
for (int i = 0; i < 4; i++)
{
String str1 = "insert into Table2(Code, Model, Num, Qty) select Code, Model, Num, Qty from Table1;";
SqlCommand xp1 = new SqlCommand(str1, con);
con.Open();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = xp1;
DataSet ds1 = new DataSet();
da1.Fill(ds1, "Code");
GridView1.DataSource = ds1;
con.Close();
}
}
}
In this program I give Number 4 manually, but I need to take it from my database qty. How can I put the SQL column name qty in the loop to insert the data at multiple time?
You can give a try like this:
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
int j = 0;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand("Your SQL Statement Here", connection);
adapter.Fill(ds);
connection.Close();
for(j=0;j<=ds.Tables[0].Rows.Count;j++){
for (i = 0; i <= Convert.ToInt32(ds.Tables[0].Rows[j]["Qty"].ToString()); i++)
{
String str1 = "insert into Table2(Code, Model, Num, Qty)
select Code, Model, Num, Qty from Table1;";
SqlCommand xp1 = new SqlCommand(str1, con);
con.Open();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = xp1;
DataSet ds1 = new DataSet();
da1.Fill(ds1, "Code");
GridView1.DataSource = ds1;
con.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I hope it is clear now. !
As pointed out in the comments, duplicating rows isn't a good idea without a primary key on both the source and destination tables, as otherwise identification of rows will become problematic.
You haven't mentioned whether you want to copy just one row, multiple rows, or the whole table N times over, but assuming the latter, bulk IO jobs like this is better suited to doing the whole operation within the database server, in order to reduce the IO transferring data back and forth between your app and the database.
Assuming both tables are in the same database, here's a way you can do this with a row-duplicating recursive CTE. If you need to control the #CopyCount from C#, just bind it as an integer and execute it with SqlCommand.ExecuteNonQuery:
DECLARE #CopyCount INT = 10;
with cteRowGen AS
(
SELECT 1 AS RowNum
UNION ALL
SELECT RowNum + 1
FROM cteRowGen
WHERE RowNum < #CopyCount
)
insert into Table2(Code,Model,Num,Qty)
select Code,Model,Num,Qty
from table1 CROSS JOIN cteRowGen;
Like StuartLC pointed out, CTE is the way to go.
Here's a version that will read the QTY from your table1
It will also insert 1 for the Qty in Table2, and not 4
DECLARE #Cnt INT = (SELECT Qty FROM Table1);
WITH data AS (
SELECT 1 AS RowCnt
UNION ALL
SELECT RowCnt + 1
FROM data
WHERE RowCnt < #Cnt
)
INSERT INTO Table2
SELECT Code, Model, Num, 1 as Qty
FROM Table1 a
CROSS JOIN data

Getting error while inserting table in database?

i am inserting table in database using table datatype with the following code:
CREATE TYPE BackUpDoctorLocationAreaRoom AS TABLE (
[RoomId] bigint,
[AreaId] bigint,
[LocationId] bigint
);
Alter proc proc_tblBackUpDoctorInsert
(
#Id uniqueidentifier='',
#BackUpDoctorId uniqueidentifier='1323e1f4-7a93-4b45-9a9b-3840c32fd6d8',
#StartDate datetime='11/08/2012',
#EndDate datetime='11/09/2012',
#StartTime datetime='22:22:22',
#EndTime datetime='01:11:11',
#CreatedBy uniqueidentifier='acf7961c-4111-49ad-a66a-ce7f9ce131bd',
#ModifiedBy uniqueidentifier='acf7961c-4111-49ad-a66a-ce7f9ce131bd',
#createdDate datetime='11/6/12 3:09:58 AM',
#ModifiedDate datetime='11/6/12 3:09:58 AM',
#tblBackUpDoctorsForRooms BackUpDoctorLocationAreaRoom READONLY
)
as
set xact_abort on
declare #newId uniqueidentifier;
set #newId = newid();
insert into tblBackUpDoctor (Id,BackUpDoctorId,StartDate,EndDate,StartTime,EndTime,CreatedBy,ModifiedBy,
createdDate,ModifiedDate,IsActive,isdeleted) values
(#newId,
#BackUpDoctorId,
#StartDate,
#EndDate,
#StartTime,
#EndTime,
#CreatedBy,
#ModifiedBy,
#createdDate,
#ModifiedDate,
1,0)
declare #IdFortblBackUpDoctorsForRooms uniqueidentifier;
set #IdFortblBackUpDoctorsForRooms = newid();
delete from tblBackUpDoctorsForRooms where BackUpRecordId=#id and Roomid in (Select roomid from #tblBackUpDoctorsForRooms)
delete from tblbackupdoctor where id=#id
insert into tblBackUpDoctorsForRooms (BackUpRecordId,Roomid,Araeid,locationid)
Select #newId,roomid,areaid,locationid from #tblBackUpDoctorsForRooms
select #newId
This is the sp in which i am using that table.
My class file's code is :
public string InsertBackUpDoctor(ClsBackUpDoctorProp objProp, DataTable dtLocAreaRoom)
{
String ConnectionString = CCMMUtility.GetCacheForWholeApplication();
String backUpRecordId = "";
SqlParameter[] param = new SqlParameter[12];
param[0] = new SqlParameter("#Id", objProp.Id);
param[1] = new SqlParameter("#BackUpDoctorId", objProp.BackUpDoctorId);
param[2] = new SqlParameter("#StartDate", objProp.StartDate);
param[3] = new SqlParameter("#EndDate", objProp.EndDate);
param[4] = new SqlParameter("#StartTime", objProp.StartTime);
param[5] = new SqlParameter("#EndTime", objProp.EndTime);
param[6] = new SqlParameter("#CreatedBy", objProp.CreatedBy);
param[7] = new SqlParameter("#ModifiedBy", objProp.ModifiedBy);
param[8] = new SqlParameter("#createdDate", CCMMUtility.GetCurrentDateTimeByTimeZone("US Mountain Standard Time"));
param[9] = new SqlParameter("#ModifiedDate", CCMMUtility.GetCurrentDateTimeByTimeZone("US Mountain Standard Time"));
param[10] = new SqlParameter("#CurrentDate", objProp.CurrentDate);
param[11] = new SqlParameter("#tblBackUpDoctorsForRooms ", dtLocAreaRoom);
backUpRecordId = SqlHelper.ExecuteScalar(ConnectionString, "proc_tblbackupdoctorInsertBackUpDoctors", param).ToString();
return backUpRecordId;
}
and here is the error which is coming when i tries to insert :
The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Table-valued parameter 12 ("#tblBackUpDoctorsForRooms"), row 0, column 0: Data type 0xF3 (user-defined table type) has a non-zero length database name specified. Database name is not allowed with a table-valued parameter, only schema name and type name are valid.
I dont know why this coming please help me..
I believe you'd have to change the way you pass your custom parameter:
Not just
param[11] = new SqlParameter("#tblBackUpDoctorsForRooms ", dtLocAreaRoom);
but rather something like
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#tblBackUpDoctorsForRooms";
parameter.SqlDbType = System.Data.SqlDbType.Structured;
parameter.TypeName = "BackUpDoctorLocationAreaRoom";
parameter.Value = dtLocAreaRoom;
param[11] = parameter;
try
parameter.SqlDbType = System.Data.SqlDbType.Structured;
parameter.TypeName = "BackUpDoctorLocationAreaRoom";
and in the call add
backUpRecordId = SqlHelper.ExecuteScalar(ConnectionString,CommandType.StoredProcedure
"proc_tblbackupdoctorInsertBackUpDoctors", param).ToString();

Resources