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
Related
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.");
}
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);
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
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
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..