Get value from stored procedure - c#

i have the following stored procedure in sql server and i am trying to take the permission value with C#.
CREATE PROCEDURE [dbo].[GetPermission]
#userName varchar(50),
#permission int output
AS
BEGIN
select #permission = PERMISSION from USERS where UserName = #userName
END;
My C# code is the following:
SqlCommand cmd = new SqlCommand(
"sp_getPermission", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(
new SqlParameter("#UserName", textBox1.Text));
cmd.Parameters.Add(
new SqlParameter("#permission", "none"));
SqlDataReader rdr = null;
rdr = cmd.ExecuteReader();
MessageBox.Show( rdr["Permission"].ToString() );
But i get the following error on the last line of C# code:
Invalid attempt to read when no data is present.
Any suggestions?

Let's simply this:
first, remove the output parameter #permission, then, change your procedure like this:
CREATE PROCEDURE [dbo].[GetPermission]
#userName varchar(50)
AS
BEGIN
select PERMISSION from USERS where UserName = #userName
END;
and for read the permission, use the ExecuteScalar method:
SqlCommand cmd = new SqlCommand(
"sp_getPermission", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(
new SqlParameter("#UserName", textBox1.Text));
var permission = (System.Int32)cmd.ExecuteScalar();

You need to set the ParameterDirection of the permission parameter on the SqlCommand to ParameterDirection.Output
Also, as you are not resulting a resultset, no need to use ExecuteReader. Just do:
cmd.ExecuteNonQuery();

You need to Read your SqlDataReader:
rdr = cmd.ExecuteReader();
if (rdr.HasRows()){
rdr.Read()
MessageBox.Show( rdr["Permission"].ToString() );
rdr.Close()
}
However, I don't believe you need a SqlDataReader for this situation. The following should work:
cmd.Parameters.Add(
new SqlParameter("#permission", "none"));
cmd.Parameters["#permission"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
MessageBox.Show(cmd.Parameters["#permission"].Value);

Related

How to set SQL Server procedure variables to inputted data from C# ASP.NET MVC program?

When using this code, I get an error
Procedure or function 'Registration' expects parameter '#qUsername', which was not supplied
Can someone please tell me how to fix this? This is my controller code and the SQL query for registration
public ActionResult Create([Bind(Include = "UserID,Username,FirstName,LastName,Email,Password,Number,IsAdmin,Salt")] UsersTable usersTable)
{
if (ModelState.IsValid)
{
Int32 rowsAffected;
SqlCommand cmd = new SqlCommand();
SqlConnection sqlConnection1 = new SqlConnection(#"xxx");
cmd.CommandText = "dbo.Registration";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
sqlConnection1.Close();
return RedirectToAction("Index");
}
return View(usersTable);
}
Procedure code:
CREATE PROCEDURE dbo.Registration
#qUsername NVARCHAR(50),
#qPassword NVARCHAR(50),
#qFirstName NVARCHAR(40),
#qLastName NVARCHAR(40),
#errorResponse NVARCHAR(250) OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE #salt UNIQUEIDENTIFIER = NEWID()
BEGIN TRY
INSERT INTO dbo.UsersTable (UserID, Password, Salt, FirstName, LastName)
VALUES (#qUsername, HASHBYTES('SHA2_512', #qPassword + CAST(#salt AS NVARCHAR(36))), #salt, #qFirstName, #qLastName)
SET #errorResponse = 'Success'
END TRY
BEGIN CATCH
SET #errorResponse = ERROR_MESSAGE()
END CATCH
END
You need to define and set the parameters for the stored procedure before your call it from your C# code - like this:
cmd.CommandText = "dbo.Registration";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
// define and set parameters!
cmd.Parameters.Add("#qUsername", SqlDbType.NVarChar, 50).Value = .....;
cmd.Parameters.Add("#qPassword", SqlDbType.NVarChar, 50).Value = .....;
cmd.Parameters.Add("#qFirstName", SqlDbType.NVarChar, 40).Value = .....;
cmd.Parameters.Add("#qLastName", SqlDbType.NVarChar, 40).Value = .....;
cmd.Parameters.Add("#errorResponse", SqlDbType.NVarChar, 250).Direction = ParameterDirection.Output;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
sqlConnection1.Close();
Use the following:
cmd.Parameters.AddWithValue("#qUsername", "xxxxx");
For all parameters before calling:
cmd.ExecuteNonQuery();

Calling stored procedure from c# returns "?????" in varchar response

When I call a stored procedure on a SQL-Server from C#, using ADO.NET, I receive following response in my output-parameter:
Literally ?????? as a VarChar.
My stored procedure looks like this:
ALTER Procedure [sp_getEncryptedPassword]
(#PublicKey nvarchar(128), #UserId uniqueidentifier, #PasswordClearText varchar(255) OUTPUT, #resOUT int OUTPUT, #rowsOUT int OUTPUT)
AS
SET NOCOUNT On
DECLARE #LinkIsValid bit = 0;
set #rowsOUT=0
while (#LinkIsValid=0)
begin
SELECT CONVERT(nvarchar, DecryptByPassphrase(#PublicKey, UserpasswordEncrypted, 1, CONVERT(varbinary, #UserId))) AS PassWordClearText
Into #TEMP1
from UserLogin
WHERE Userid = #UserId
set #rowsOUT=##ROWCOUNT
SET #LinkIsValid=1
end
if #rowsOUT=0
SET #resOUT=1
select 'RStestPwd' as 'PasswordClearText', #resOUT as 'resOUT', #rowsOUT as 'rowsOUT'
I have removed some lines, but I hope you get the point.
As part of debugging, I have hardcoded a response - just to see if I get anything. And I do:
My C# code:
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand(spName, con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter pubKey = cmd.Parameters.Add("#PublicKey", SqlDbType.UniqueIdentifier);
pubKey.Direction = ParameterDirection.Input;
pubKey.Value = publicKey;
SqlParameter IdIn = cmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier);
IdIn.Direction = ParameterDirection.Input;
IdIn.Value = userid;
SqlParameter pwdOUT = cmd.Parameters.Add("#PasswordClearText", SqlDbType.VarChar, 255);
pwdOUT.Direction = ParameterDirection.Output;
SqlParameter resOUT = cmd.Parameters.Add("#resOUT", SqlDbType.Int);
resOUT.Direction = ParameterDirection.Output;
SqlParameter rowsOUT = cmd.Parameters.Add("#rowsOUT", SqlDbType.Int);
rowsOUT.Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
result.Password = pwdOUT.Value.ToString();
Is it a part of the formatting between the SQL-server and my application?
Is it a setting in my SQL-server, my ADO.NET Command instance or my conntection string?
EDIT:
Thanks for your comments. I have reviewed my code, and modyfied places with (N)VarChar and so on.
Neither before or after these modifications, I get any exceptions - just the questionmarks. So the SP is working - but loose/modify data between database and application...

C# SQL Server update doesn't work

I have this code, and when I execute it, it doesn't work
SqlCommand cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = 'username', pass = '#password' where IDetudient='#ID ' ", con);
con.Open();
cmd.Parameters.AddWithValue("#username", text_name.Text);
cmd.Parameters.AddWithValue("#password",Convert.ToDecimal( textBox1.Text));
cmd.Parameters.AddWithValue("#ID", Convert.ToInt64( text_id.Text));
cmd.ExecuteNonQuery();
con.Close();
Try this way:
SqlCommand cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = #username, pass = #password where IDetudient=#ID", con);
I had the same issue. The thing is, in the query you just pass the name of the parameter.
Your sql command't test would be:
var cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = #username, pass = #password where IDetudient = #ID ", con);
Also, you will need to validate if conversion from string to int64 if fails or not.

How To Get Set Value From Stored procedure in C#

I have a stored procedure that client provided me
Like:
ALTER Proc [dbo].[XYZ]
#Parameter varchar(100),
#Parameter1 nvarchar(4000) out
SET #APIString = "Test Test"
I have no rights to change this procedure.
When I execute procedure through C# I get a blank string from procedure
How to get the #Parameter1 value in my project?
C# Code:
SqlCommand cmd = new SqlCommand("dbo.XYZ", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Parameter", Parameter);
cmd.Parameters.Add("#Parameter1", SqlDbType.VarChar,4000);
cmd.Parameters["#Parameter1"].Direction = ParameterDirection.Output;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
String = reader["#Parameter1"] != null ? reader["#Parameter1"].ToString() : "";
}
conn.Close();
#Parameter1 is an output parameter. You can get its value the same way you set the values for input parameters, e.g.
var cmd = new SqlCommand("dbo.XYZ", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Parameter", inputValue);
// add the output parameter
cmd.Parameters.Add("#Parameter1", SqlDbType.NVarChar).Direction =
ParameterDirection.Output;
cmd.ExecuteNonQuery();
string parameter1 = (string)cmd.Parameters["#Parameter1"].Value;
You should also use ExecuteNonQuery unless the store procedure returns values with a select statement.

Update Command with stored procedure

I have an update query(stored procedure) which is working properly in SQL Server when I execute it.
CREATE PROCEDURE updatestudenthws(#stdid nvarchar(50),#hwid int, #grade float)
AS
UPDATE Table_Exercise_Answer
SET
ExAns_Grade = #grade
WHERE ExAns_Exercise = #hwid AND ExAns_Student = #stdid
but when I run the program it does not have any effect in my table and also I don't have any error.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#hwid", SqlDbType.VarChar);
cmd.Parameters.Add("#stdid", SqlDbType.VarChar);
cmd.Parameters.Add("#grade", SqlDbType.VarChar);
cmd.Parameters["#hwid"].Value = hwid;
cmd.Parameters["#stdid"].Value = studentid;
cmd.Parameters["#grade"].Value = grade;
cmd.ExecuteNonQuery();
con.Close();
What is my mistake?
How should I do this work?
Use AddWithValue(), so you don't have to provide the type, which allowed you to make the mistake of passing varchar to an int parameter.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#hwid", hwid);
cmd.Parameters.AddWithValue("#stdid", studentid);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
con.Close();
Your ADO.NET code defining the parameters for the stored procedure is wrong in that you don't define the parameters with their proper datatypes.
Your stored procedure defines:
#stdid nvarchar(50) --> but you define it as varchar
#hwid int --> but you define it as varchar
#grade float --> but you define it as varchar
You need to change your code to this:
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#hwid", SqlDbType.Int); // this needs to be SqlDbType.Int
cmd.Parameters.Add("#stdid", SqlDbType.NVarChar, 50); // this should be SqlDbType.NVarChar and specify its proper length
cmd.Parameters.Add("#grade", SqlDbType.Float); // this needs to be SqlDbType.Float
when you use AddWithValue(), don't you have to provide the type passing like varchar to an int parameter.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#hwid", hwid);
cmd.Parameters.AddWithValue("#stdid", studentid);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
con.Close();

Categories

Resources