When calling stored procedure, .hasRows keeps staying "false" - asp.net

I have a stored procedure which I am calling which will return data from a table.
But when I try to populate an .aspx with the data it skips my method from doing it because my method is based on whether a reader detects rows.
Here is my method:
private void editExhibit(int expenseID)//new
{
saveExhibitBtn.Text = "Update Exhibit";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("p_CaseFiles_Exhibits_RetrieveExhibitDetails", conn);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("#ExhibitID", expenseID);
cmd.Parameters.Add(new SqlParameter("#ExhibitID", SqlDbType.Int));
cmd.Parameters["#ExhibitID"].Value = expenseID;
bool hasAttachments = false;
string investigatorID = "";
//bool alreadyInvoiced = false;
bool isExpenseOwner = false;
string fileID = "-1";
try
{
conn.Open();
var reader = cmd.ExecuteReader();
if (reader.HasRows)//////////////////////craps out here bcause hasRows is false....
{
reader.Read();
fileID = reader["FileID"].ToString();
ddlCaseFiles.SelectedValue = fileID;
ddlCaseFiles.Enabled = false;
// retrieve exhibit details here
hasAttachments = (bool)reader["HasAttachments"];
investigatorID = reader["InvestigatorID"].ToString();
if (Session["InvestigatorID"].ToString() == investigatorID)
{
isExpenseOwner = true;
}
txtDateReceived.Value = reader["SeizeDate"].ToString();
ddlReceivedBy.SelectedValue = reader["SeizedByInvestigatorID"].ToString();
txtTimeReceived.Value = reader["SeizeTime"].ToString();
txtWhyHowReceived.Value = reader["SeizeAuthority"].ToString();
txtReceivedLocation.Value = reader["SeizeLocation"].ToString();
txtOurItemNum.Value = reader["NewExhibitOutItemNumber"].ToString();////////////
txtTheirItemNum.Value = reader["ClientItemNum"].ToString();
txtBagNum.Value = reader["BagNumber"].ToString();
txtBoxNum.Value = reader["BoxNumber"].ToString();
txtComment.Value = reader["ExhibitDecriptionPlainText"].ToString();
}
}
catch (SqlException ex)
{
ErrorLogger.Log(ex.Number, "NewExhibit.aspx - editExhibit - Retrieve Details", ex.Message);
}
Here is my stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[p_CaseFiles_Exhibits_RetrieveExhibitDetails]
#FilterField nvarchar(max)=null
, #FilterQuery nvarchar(max)=null
, #SortName nvarchar(max)='SeizeDate, SeizeTime '
, #SortOrder nvarchar(max)='desc'
, #ExhibitID int
as
SET CONCAT_NULL_YIELDS_NULL OFF
declare #Command nvarchar(max)
Select #Command = 'select E.ExhibitID,convert(nvarchar,SeizeDate,111) as ''SeizeDate'',SeizeTime,ExhDesc,E.InvestigatorID as ''EnteredBy''
,E.SeizedByInvestigatoID as ''SeizedBy'',SBI.ActiveInvestigator, SBI.FName+'' '' + SBI.LName as ''SeizedByName'', E.FileID,[FileName]
,Investigators.FName,Investigators.LName,SzAuthority,Location,ItemID,SubItemID1,SubItemID2,SubItemID3,PageSerial,ClientItemNum,Privileged
,Private,E.HasAttachments,ItemEntryGradeID,BagNumber,BoxNumber,PL.PropertyId,P.PropertyTypeID,P.PropertyMakeID,P.PropertyModelID,SerialNumber,ColorID
,cast(ItemID as varchar)+''-''+cast(SubItemID1 as varchar)+''-''+cast(SubItemID2 as varchar)+''-''+cast(SubItemID3 as varchar) as ''ItemNumber'',StoredLocally
from CaseFileExhibits E
join Investigators on E.InvestigatorID = Investigators.InvestigatorID
join Investigators SBI on SBI.InvestigatorID=E.SeizedByInvestigatoID
join CaseFiles on E.FileID = CaseFiles.FileID
left join CaseFileExhibitPropertyLink PL on E.ExhibitID=PL.ExhibitID
left join Element09a_Properties P on P.PropertyID=PL.PropertyId
left join ElementPropertyTypes PT on PT.PropertyTypeID=P.PropertyTypeID
left join ElementPropertyMakes PM on PM.PropertyMakeID=P.PropertyMakeID
left join ElementPropertyModels PMD on PMD.PropertyModelID=P.PropertyModelID
where E.ExhibitID='+convert(nvarchar,#ExhibitID);
if(#FilterQuery is not null)
begin
select #Command+=' and '+#FilterField+ ' like '''+#FilterQuery+''' ';
end
select #Command+=' order by '+#SortName+' '+#SortOrder
So according to the stored procedure I only need to pass in the exhibitID, which I did.

Your Stored procedure looks incomplete. You probably need to add
exec sp_executesql #command;
At the end to get it to return your rows.
info about sp_executesql can be found at http://msdn.microsoft.com/en-us/library/ms188001.aspx

Related

How can I get data from a stored procedure that contains a Cursor with another Cursor inside it

How can I get data from a stored procedure that contains a cursor with another cursor inside it in ASP.NET ?
When I try this code, I get the following error:
Unsupported Oracle data type RSET encountered
I need to fetch data from oracle and transfer it to a web service
Oracle 9i
This is the stored procedure and the code that I work on:
PROCEDURE P_GET_VST_CLAIMS_CLAIMSDTL ( P_PAGE_SIZE NUMBER, P_PAGE_NUMBER NUMBER, P_VST_ID NUMBER, P_PAT_ID NUMBER, P_REFCUR OUT SYS_REFCURSOR )
IS
/*
P_REFCUR_DATA STRUCTURE
----------------------------------------------------------------
VST_ID,
OL2CLAIMS_ID,
CLM_DATE,
MPTYPE_ID,
MP_TYPE_DESC_E,
MP_TYPE_DESC_A,
CLM_MP_ID,
PROVIDER_NAME_E,
PROVIDER_NAME_A,
MP_BRANCH_ID,
MP_PART_ID,
STATUS,
STATUS_DESCE,
STATUS_DESCA,
PAT_ID,
PAT_NAME_E,
PAT_NAME_A,
CLM_AMT,
CO_INS_TOT_AMT,
ATTACHS
CLAIMDTL (REFCUR)
ID NUMBER
VST_ID NUMBER
CLM_ID NUMBER
DTL_TYPE VARCHAR2
DTL_ID NUMBER
DESC_E VARCHAR2
DESC_A VARCHAR2
HCPC_ID NUMBER
MDSN_ID NUMBER
QTY NUMBER
UNIT_DESC_E VARCHAR2
UNIT_DESC_A VARCHAR2
TQ_ID NUMBER
TQ_DESC_E VARCHAR2
TQ_DESC_A VARCHAR2
REQUESTED_REPETITION NUMBER
CLM_AMT NUMBER
PRICE_LIST_AMT NUMBER
PRICE_LIST_REJ_AMT NUMBER
CO_INS_TOT_AMT NUMBER
CO_INS_DESERVED_AMT NUMBER
TPA_MP_SERVICE_AMT NUMBER
MP_DISC_AMT NUMBER
MP_NET_AMT NUMBER
*/
C# code:
[HttpPost]
[Obsolete]
public IHttpActionResult P_GET_VST_CLAIMS_CLAIMSDTL([FromBody] OracleParameters model)
{
IHttpActionResult httpActionResult;
try
{
string UsernameConfig = WebConfigurationManager.AppSettings["AppUsername"];
string PasswordConfig = WebConfigurationManager.AppSettings["AppPassword"];
if (model.AppUserName != UsernameConfig)
{
httpActionResult = this.Return_Response(false, 5, "Application Username Or Password not correct", null);
}
else if (model.AppPassword == PasswordConfig)
{
using (OracleConnection connection = new OracleConnection("Data Source= (DESCRIPTION = (ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.0.2)(PORT = 1521)))(CONNECT_DATA =(SERVICE_NAME = db1))); User Id=coreapps; Password=coreapps;"))
{
OracleDataAdapter da = new OracleDataAdapter();
OracleCommand cmd = new OracleCommand()
{
Connection = connection,
CommandText = "PKG_COREAPPS.P_GET_VST_CLAIMS_CLAIMSDTL",
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.Add("P_PAGE_SIZE", OracleType.Number).Value = model.P_PAGE_SIZE;
cmd.Parameters.Add("P_PAGE_NUMBER", OracleType.Number).Value = model.P_PAGE_NUMBER;
cmd.Parameters.Add("P_VST_ID", OracleType.Number).Value = model.P_VST_ID;
cmd.Parameters.Add("P_PAT_ID", OracleType.Number).Value = model.P_PAT_ID;
cmd.Parameters.Add("P_REFCUR", OracleType.Cursor).Direction = ParameterDirection.Output;
connection.Open();
OracleDataAdapter da1 = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
da1.Fill(ds);
ClsLog.TextLog(ds.Tables[0].Rows[0][0].ToString());
connection.Close();
httpActionResult = this.Return_Response1(true, 1, "Success", ds);
}
}
else
{
httpActionResult = this.Return_Response(false, 5, "Application Username Or Password not correct", null);
}
}
catch (Exception exception)
{
Exception ex = exception;
ClsLog.OnError(ex);
httpActionResult = this.Return_Response(false, 3, ex.Message, null);
}
return httpActionResult;
}

Stored procedure with input & output parameters and 2 recordsets

I try to extract the results in c# asp.net from my stored procedure but it has 2 recordsets. the first with 1 row and the second with many rows as dates.
The code
public string penth_slqDAYS(string connectionString)
{
string sMonth = DateTime.Now.Month.ToString();
string syear = DateTime.Now.Year.ToString();
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command1 = new SqlCommand("penthhmera_proc", connection);
/////////////////////////////
SqlParameter param1;
param1 = command1.Parameters.Add("#prs_nmb_pen", SqlDbType.VarChar, 7);
param1.Value = prs_nmb_lb1.Text.Trim();
SqlParameter param2;
param2 = command1.Parameters.Add("#month_pen", SqlDbType.Int);
param2.Value = sMonth;
SqlParameter param3;
param3 = command1.Parameters.Add("#year_int", SqlDbType.Int);
param3.Value = syear;
/////////////////////////
command1.Parameters.Add("#days_out", SqlDbType.Int);
command1.Parameters["#days_out"].Direction = ParameterDirection.Output;
command1.Parameters.Add("#message_out", SqlDbType.VarChar,50);
command1.Parameters ["#message_out"].Direction = ParameterDirection.Output;
command1.Parameters.Add("#dateess_out", SqlDbType.Date);
command1.Parameters["#dateess_out"].Direction = ParameterDirection.Output;
///////////////////////////
connection.Open();
command1.CommandType = CommandType.StoredProcedure;
command1.ExecuteNonQuery();
days_penthwork_tx.Text = Convert.ToString(command1.Parameters["#days_out"].Value);
message_tx.Text = Convert.ToString(command1.Parameters["#message_out"].Value);
///the above parameter contains rows with dates
Label12.Text = Label12.Text + Convert.ToString(command1.Parameters["#dateess_out"].Value);
connection.Close();//close connection
}
return "success";
}
catch (Exception e)
{
return e.ToString();
}
}
My SQL Server stored procedure:
the results
and the query when c# run the code
declare #p4 int
set #p4 = 3
declare #p5 varchar(50)
set #p5 = 'some text'
declare #p6 date
set #p6 = NULL
exec penthhmera_proc #prs_nmb_pen = '274484',
#month_pen = 1,
#year_int = 2021,
#days_out = #p4 output,
#message_out = #p5 output,
#dateess_out = #p6 output
select #p4, #p5, #p6
I think that with that way #p6 is always null.
Finally I want to load all the values from the second recordset to a Gridview or something like a table in order to show it in my webform.
Any idea?
Thanks in advance
ExecuteReader was the answer. thnx Charlieface.
connection.Open();
command1.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = command1.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//some code
}
dr.NextResult();
while (dr.Read())
{
//some code
}
}
else
{
Console.WriteLine("No data found.");
}

Stored procedure doesn't return output

I have a simple stored procedure which inserts a users record in a table and should give out its userid.
Here is the stored procedure:
Alter proc spRegistration
#UserId nvarchar(10) output,
#Name nvarchar(20),
#EmailAdd nvarchar(20)
as
begin
Declare #Count int;
Declare #ReturnCode int
Select #Count = Count(EmailAdd)
from tblAllUsers
where EmailAdd = #EmailAdd
if #Count > 0
begin
Set #ReturnCode = -1
end
else
begin
Set #ReturnCode = 1
Insert into tblAllUsers(Name, EmailAdd)
values(#Name, #EmailAdd)
end
Select #UserId = UserId
from tblAllUsers
where EmailAdd = #EmailAdd
Select #ReturnCode as ReturnCode
end
I try to get the userid into a textbox like below :
string CS = ConfigurationManager.ConnectionStrings["hh"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spRegistration", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#EmailAdd", txtEmailAddress.Text);
var UserID = cmd.Parameters.AddWithValue("#UserId", SqlDbType.NVarChar);
UserID.Direction = ParameterDirection.Output;
int ReturnCode = (int)cmd.ExecuteScalar();
if (ReturnCode == -1)
{
lblRegMessage.Text = "This email has already been registered with us.";
}
else
{
lblRegMessage.Text = "You were registered successfully.";
txtUserId.Text=(String)UserID.Value;
}
The table as well as the stored procedure is far too complex,I have simplified it for better understanding of problem.UserId is Alphanumeric.Dont worry about that.
Putting a break point shows a null against var UserID
Where am i going wrong?
You need to Use .ToString() on UserID
txtUserId.Text= UserID.Value.ToString();
EDIT:
var UserID = cmd.Parameters.AddWithValue("#UserId", SqlDbType.NVarChar,50);

Correct syntax in stored procedure and method using MsSqlProvider.ExecProcedure?

I have problem with ASP.net and stored procedure
My procedure in SQL Server:
ALTER PROCEDURE [dbo].[top1000]
#Published datetime output,
#Title nvarchar(100) output,
#Url nvarchar(1000) output,
#Count INT output
AS
SET #Published = (SELECT TOP 1000 dbo.vst_download_files.dfl_date_public FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC )
SET #Title = (SELECT TOP 1000 dbo.vst_download_files.dfl_name FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC)
SET #Url = (SELECT TOP 1000 dbo.vst_download_files.dfl_source_url FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC)
SET #Count = (SELECT TOP 1000 dbo.vst_download_files.dfl_download_count FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC)
And my procedure in website project
public static void Top1000()
{
List<DownloadFile> List = new List<DownloadFile>();
SqlDataReader dbReader;
SqlParameter published = new SqlParameter("#Published", SqlDbType.DateTime2);
published.Direction = ParameterDirection.Output;
SqlParameter title = new SqlParameter("#Title", SqlDbType.NVarChar);
title.Direction = ParameterDirection.Output;
SqlParameter url = new SqlParameter("#Url", SqlDbType.NVarChar);
url.Direction = ParameterDirection.Output;
SqlParameter count = new SqlParameter("#Count", SqlDbType.Int);
count.Direction = ParameterDirection.Output;
SqlParameter[] parm = {published, title, count};
dbReader = MsSqlProvider.ExecProcedure("top1000", parm);
try
{
while (dbReader.Read())
{
DownloadFile df = new DownloadFile();
//df.AddDate = dbReader["dfl_date_public"];
df.Name = dbReader["dlf_name"].ToString();
df.SourceUrl = dbReader["dlf_source_url"].ToString();
df.DownloadCount = Convert.ToInt32(dbReader["dlf_download_count"]);
List.Add(df);
}
XmlDocument top1000Xml = new XmlDocument();
XmlNode XMLNode = top1000Xml.CreateElement("products");
foreach (DownloadFile df in List)
{
XmlNode productNode = top1000Xml.CreateElement("product");
XmlNode publishedNode = top1000Xml.CreateElement("published");
publishedNode.InnerText = "data dodania";
XMLNode.AppendChild(publishedNode);
XmlNode titleNode = top1000Xml.CreateElement("title");
titleNode.InnerText = df.Name;
XMLNode.AppendChild(titleNode);
}
top1000Xml.AppendChild(XMLNode);
top1000Xml.Save("\\pages\\test.xml");
}
catch
{
}
finally
{
dbReader.Close();
}
}
And if I made to MsSqlProvider.ExecProcedure("top1000", parm); I got
String[1]: property Size has invalid size of 0.
Where I should look for solution? Procedure or method?
You need to specify the length property for url and Title
SqlParameter title = new SqlParameter("#Title", SqlDbType.NVarChar);
title.Size=1000
SqlParameter url = new SqlParameter("#Url", SqlDbType.NVarChar);
url.Size=1000
Instead of using an output parameter you can change your query like the one below
ALTER PRocedure [dbo].[top1000]
As
Begin
Select top 1000 dfl_date_public ,dfl_name,dfl_source_url,
dfl_download_count from dbo.vst_download_files
order by dbo.vst_download_files.dfl_download_count DESC
Then use execute reader
SqlCommand command =
new SqlCommand("top1000", connection);
command.CommandType=CommandType.StoredProcedure
SqlDataReader reader = command.ExecuteReader();
// Iterate through reader as u did and add it to the collection
use xelement to frame the XML
foreach (DownloadFile df in List)
{
XElement products=
new XElement("Products",
new XElement("product",
new XElement("published", "data dodania"),
new XElement("title", df.Name)
);
}

Procedure or Function 'Student' expects parameter '#SortExpression', which was not supplied

I am getting this strange error I have checked the value of sort it is also not null still it giving me error my code.
public static List<MyDb_student> GetAllUsers(String sort, CustomPaging paging)
{
con.Open();
SqlCommand objParams = new SqlCommand();
objParams.Parameters.Add("#SortExpression",SqlDbType.VarChar).Value = sort;
objParams.Parameters.Add("#StartRowIndex",SqlDbType.Int).Value = paging.startRow;
objParams.Parameters.Add("#MaximumRows",SqlDbType.Int).Value = paging.maxRow;
objParams.CommandType = System.Data.CommandType.StoredProcedure;
objParams.CommandText = "clud_GetAllUsers";
objParams.Connection = con;
SqlDataAdapter objSda = new SqlDataAdapter(objParams.CommandText, con);
DataSet objDS = new DataSet();
objSda.Fill(objDS);
//to inialize the list.
List<MyDb_student> lstStudent = new List<MyDb_student>();
//to itereate through the data row.
foreach (DataRow dr in objDS.Tables[0].Rows)
{
//passing each row to the constructor to dump the values in the constructor.
MyDb_student objStu = new MyDb_student(dr);
//adding the value to the list by passing the object.
lstStudent.Add(objStu);
}
con.Close();
return lstStudent;
}
My stored proc
ALTER PROCEDURE [dbo].[clud_GetAllUsers]
#SortExpression VARCHAR(100),
#StartRowIndex INT,
#MaximumRows INT
AS
BEGIN
IF LEN(#sortExpression) = 0
SET #sortExpression = 'UserID'
DECLARE #sql nvarchar(4000)
SET #sql = 'SELECT * FROM (
SELECT UserID,UserName,EmailID,MobileNO,ROW_NUMBER() OVER (ORDER BY ' + #SortExpression + ' desc) AS RowRank
FROM UserRegistration )
AS UserRegistrationWithRowNumbers
WHERE RowRank > ' + CONVERT(nvarchar(10), #StartRowIndex) +
' AND RowRank <= (' + CONVERT(nvarchar(10), #StartRowIndex) + ' + '
+ CONVERT(nvarchar(10), #MaximumRows) + ')'
EXEC sp_executesql #sql
END
i am not able to fix it.
Instead of
IF LEN(#sortExpression) = 0
SET #sortExpression = 'UserID'
Try to add isnull to capture null:
IF LEN(ISNULL(#sortExpression, '')) = 0
SET #sortExpression = 'UserID'
Simply check as follows:
if(#sortExpression IS NULL)
SET #sortExpression = 'UserID'
hope this will solve the issue..

Resources