I tested the query on SQL Server and it works, but not on C#. The error messages point towards the storing mechanism for the variables returned by my query, but I am thinking it is probably the query itself that is the issue.
In Delphi, there is a way to debug query statements (showMessage statement).
For example:-
DMS.ADOQuery1.SQL.Clear;
DMS.ADOQuery1.SQL.Add('select FIRSTNM, LASTNM, STREET, STREET2, CITY, STATE, ZIP, MEMBERKEY, MEMBID, BIRTH' +
' from MEMBER' +
' where MEMBID = ''' + Mem_ID + ''''
);
showmessage(DMS.ADOQuery1.SQL[0]);
Is there a way to do something similar in C# ?
Could anyone take a look and let me know why the SQL query doesn’t work in ASP.net but works in SQL Server?
// initialize
string [] HPCODE = new string[20] ;
string [] OPFROMDT = new string [20] ;
string [] OPTHRUDT = new string [20] ;
// Second SQL Query to find out eligibility information about the requested Member. //
SqlConnection Connection1 = new SqlConnection(DBConnect.SqlServerConnection);
String strSQL1 = "SELECT MEMBER, HPCODE, convert(varchar, OPFROMDT, 101) as OPFROMDT, convert(varchar, OPTHRUDT, 101) as OPTHRUDT FROM [main].[dbo].[MEMBER] INNER JOIN [main].[dbo].[MEMBHP] ON MEMBER.MEMBERKEY = MEMBHP.MEMBERKEY and opthrudt >= opfromdt INNER JOIN [main].[dbo].[HPCONTRACT] ON MEMBHP.HPCODEKEY = HPCONTRACT.HPCODEKEY INNER JOIN [main].[dbo].[LOB] ON HPCONTRACT.LOB_KEY = LOB.LOB_KEY where MembID = @memID";
SqlCommand command1 = new SqlCommand(strSQL1, Connection1);
//command1.Parameters.AddWithValue("@memID", memID);
// SQL reader variable is set.
SqlDataReader Dr1;
// Connection is explicitly opened.
Connection1.Open();
// Reader is executed.
Dr1 = command1.ExecuteReader();
int i = 0;
while (Dr1.Read())
{
// if (memID == Dr["MEMBID"].ToString() )
// {
// store subID in the Global variable called ID.
HPCODE[i] = (Dr1["HPCODE"].ToString()).TrimEnd();
OPFROMDT[i] = (Dr1["OPFROMDT"].ToString()).TrimEnd();
OPTHRUDT[i] = (Dr1["OPTHRUDT"].ToString()).TrimEnd();
i = i + 1;
// }
}
// Reader variable must always be explicitly closed to prevent memory leaks.
Dr1.Close();
Error:
Index out of range Exception unhandled by user code:=HPCODe
NOTE:-
Parameters.AddwithValue is uncommented because it is predefined in my previous part of the code. If the solution was that easy, I would have fixed it myself.*
You have more than 20 rows returning, so you are erroring when trying to fill the 21st row in your loop. This isn’t a SQL issue; it’s a coding issue.
As a quick fix, you can do the following. However, you may want to make a class to hold your information if it’s all related and make a
Listof that class.In your loop, you’d want the following: