Stored procedure doesn't return output - asp.net

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);

Related

I can't capture the output of a procedure

When debugging a function that allows me to create a record, I can't get the output of the procedure. 'Output' never changes its value with which it is initialized ("").
string Agregar(Empleado reg)
{
string mensaje = "";
string output = "";
SqlConnection cn = new SqlConnection(cadena);
try
{
cn.Open();
SqlCommand cmd = new SqlCommand("sp_pregunta02_3 #codEmp,#nom,#ape,#idpais,#email", cn);
cmd.Parameters.AddWithValue("#nom", reg.nomEmployee);
cmd.Parameters.AddWithValue("#ape", reg.apeEmployee);
cmd.Parameters.AddWithValue("#idpais", reg.idpais);
cmd.Parameters.AddWithValue("#email", reg.emailEmployee);
cmd.Parameters.Add("#codEmp", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
output = cmd.Parameters["#codEmp"].Value.ToString();
mensaje = $"El codigo {output} ya existe";
if (!output.Equals("0"))
mensaje = $"Se ha registro el Empleado de codigo {output}";
}
catch (SqlException ex)
{
mensaje = ex.Message;
}
finally
{
cn.Close();
}
return mensaje;
}
The procedure returns a random employee code from a function that generates random numbers that are not in the table, if it already exists it returns 0.
CREATE OR ALTER PROCEDURE sp_pregunta02_3
#codEmp int OUTPUT,
#nom varchar(255),
#ape varchar(255),
#idpais char(3),
#email varchar(255)
AS
BEGIN
SET #codEmp = dbo.fn_pregunta02();
PRINT #codEmp
IF #codEmp <> 0
BEGIN
INSERT INTO tb_employee
VALUES (#codEmp, #nom, #ape, #idpais, #email)
END
END
Try this code:
SqlCommand cmd = new SqlCommand("sp_pregunta02_3, cn);
cmd.Parameters.Add("#nom", SqlDbType.VarChar).Value = reg.nomEmployee;
cmd.Parameters.Add("#ape", SqlDbType.VarChar).Value = reg.apeEmployee;
cmd.Parameters.Add("#idpais", SqlDbType.Char).Value = reg.idpais;
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = reg.emailEmployee;
cmd.Parameters.Add("#codEmp", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
output = cmd.Parameters["#codEmp"].Value.ToString();
In stored procedure you must select the output
CREATE OR ALTER PROCEDURE sp_pregunta02_3
#codEmp int output,
#nom varchar(255),
#ape varchar(255),
#idpais char(3),
#email varchar(255)
as
BEGIN
SET #codEmp = dbo.fn_pregunta02();
PRINT #codEmp
IF #codEmp <> 0
BEGIN
insert into tb_employee
values(#codEmp, #nom, #ape, #idpais, #email)
END
select #codEmp
END

When calling stored procedure, .hasRows keeps staying "false"

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

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)
);
}

Why insert statement generates 2 rows?

I dont know why, but when I do an insert statement in my project, its generate 2 indentical rows instead of makeing just one.
why is that ?
this is my code :
if (ListBox.Items.Count != 0)
{
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string arr = "";
for (int i = 0; i < ListBox.Items.Count; i++)
{
arr += ListBox.Items[i] +",";
}
string sqlqueryString = "INSERT INTO HistoryOfGames (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID,Arrayarray) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID, #Arrayarray);" + "SELECT SCOPE_IDENTITY()";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.Parameters.AddWithValue("Arrayarray", arr);
commandquery.ExecuteNonQuery();
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
con.Close();
Response.Redirect("NowPlay.aspx?ID="+ IdOfRecentHistoryGame);
}
You're running it twice, ExecuteNonQuery() and ExecuteScalar(). Get rid of the ExecuteNonQuery().
you do
commandquery.ExecuteNonQuery();
then right after
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
you do execute it twice
and don't forget to check for sql injection in your code...
I'd check two things:
see how many times this statement is executed (try setting a breakpoint to verify that the code is only run once)
see if there are any triggers in the database that might cause an extra record to be inserted
I had the same problem,I handled it this way.not professional but it works:
Dim x As Boolean = True
If x = True Then
here goes your code to insert to database.
End If
x = False

Refuses to make ExecuteNonQuery : Incorrect syntax near '('

Im trying to insert data to my database, and it gives me an error :
Incorrect syntax near '('.
This is my code :
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string sqlqueryString = "INSERT INTO (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID)";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.ExecuteNonQuery();
con.Close();
I run it in debug mode, and its accepting everything until the "ExecuteNonQuery();" line.
anybody has a clue what I did wrong?
Thanks!
you did this:
INSERT INTO (GameID....
but should do this:
INSERT INTO tablename (GameID....
Your INSERT INTO statement is missing the name of the table into which it is supposed to insert.
The syntax of your insert into statement is incorrect as you are not specifying which table you are inserting into.
The correct syntax is
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
See : http://www.w3schools.com/sql/sql_insert.asp for more information

Resources