I have the following SQL code:
CREATE PROCEDURE [dbo].[sproc_tblUser_GetAllInfo]
@Email NCHAR(25),
@UserID INT
AS
SELECT
tblUser.Firstname, tblUser.Lastname, tblPersonal.Age, tblPersonal.Sex
FROM
tblUser, tblPersonal
WHERE
tblUser.UserID = @UserID AND tblPersonal.UserID = @UserID
IF @@ROWCOUNT = 0
SELECT Firstname, Lastname
FROM tblUser
WHERE UserID = @UserID
RETURN @@IDENTITY
This stored procedure is run within the following:
protected void Page_Load(object sender, EventArgs e)
{
//copy email from query string
Email = Convert.ToString(Request.QueryString["Email"]);
lblWelcome.Text = "Welcome to Love Finder, " + Email;
UserID = Convert.ToInt32(Request.QueryString["UserID"]);
//add params
db.AddParameter("Email", Email);
db.AddParameter("UserID", UserID);
//execute GetAllInfo query
db.Execute("sproc_tblUser_GetAllInfo");
//if entries in both tables found, do this
if (db.Count == 1)
{
//get parameters
User.ThisID.Firstname = Convert.ToString(db.DataTable.Rows[0]["Firstname"]);
User.ThisID.Lastname = Convert.ToString(db.DataTable.Rows[0]["Lastname"]);
User.ThisID.Sex = Convert.ToString(db.DataTable.Rows[0]["Sex"]);
User.ThisID.Age = Convert.ToInt32(db.DataTable.Rows[0]["Age"]);
//send to text boxes
txtName.Text = Convert.ToString(User.ThisID.Firstname + "" + User.ThisID.Lastname);
txtAge.Text = Convert.ToString(User.ThisID.Age);
txtSex.Text = Convert.ToString(User.ThisID.Sex);
}
else
{
//if only one table entry found (User), do this
User.ThisID.Firstname = Convert.ToString(db.DataTable.Rows[0]["Firstname"]);
User.ThisID.Lastname = Convert.ToString(db.DataTable.Rows[0]["Lastname"]);
txtName.Text = Convert.ToString(User.ThisID.Firstname + "" + User.ThisID.Lastname);
}
}
The query relies on there being columns in both the User and Personal table. If I run the application with a member who has entered columns into both tables, it returns what I want it to. However, for the sub query that only collects data from the User table, I get the following error:
An exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll but was not handled in user code
Additional information: There is no row at position 0.
TLDR:
When I execute the query by itself by giving it the parameters its being passed by the query string, it works and returns what it should. But, when run through the code, I'm getting the above error.
Can anyone shed light on this? It's probably something glaringly obvious, but I'm quite new to C# programming.
Kind regards
@@Identityshould be used withSELECT INTOorINSERT. It is not appropriate for a mereSELECT. What are you trying to accomplish?dbhere? because it isn't raw ADO.NETdb.Countis 0, then we would expectRows[0]to throw an indexoutofrangeJOINsyntax in the ANSI-92 SQL Standard (more than 25 years ago) and its use is discouraged