c# error "Procedure 'spReturnLastRowNoteID' expects param '#noteid', which was not supplied." though I don't have input parameter in sp - c

ALTER PROCEDURE dbo.spReturnLastRowNoteID
(#noteid int OUTPUT)
AS
SET NOCOUNT ON
SELECT #noteid = NoteID
FROM NoteTable
WHERE NoteID = IDENT_CURRENT('NoteTable')
RETURN #noteid`
I don't think there is a problem in my sp and code but I'm not sure why i'm getting the error:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sqlSearchCommand = "spReturnLastRowNoteID";
SqlCommand command = new SqlCommand(sqlSearchCommand, connection);
command.CommandType = CommandType.StoredProcedure;
SqlParameter noteid = command.Parameters.Add("#noteid", SqlDbType.Int);
noteid.Direction = ParameterDirection.ReturnValue;
command.ExecuteNonQuery();
lastnoteid = (int)command.Parameters["#noteid"].Value;
}

Try setting the parameters direction to Output.
noteid.Direction = ParameterDirection.Output;

Related

Conversion failed when converting from a character string to uniqueidentifier - Doesn't Rollback the transaction

The actual issue is not this - "Conversion failed when converting from a character string to uniqueidentifier" but the issue is that, the transaction doesn't get rolled back after you hit the issue.
My code here,
var connectionstring = "Server= ****; Database= ****; Integrated Security=True;";
var errorInformation = new List<string>();
using (SqlConnection objConn = new SqlConnection(connectionstring))
{
objConn.Open();
var objTrans = objConn.BeginTransaction(); // Begins here
var sql = $"insert into tblProject values('7', 'TestProject')";
SqlCommand insertCommand = new SqlCommand(sql, objConn, objTrans);
try
{
insertCommand.ExecuteNonQuery();
// ProjectID is a unique Identifier in database
SqlCommand cmd = new SqlCommand("SELECT * FROM SOMEOTHERTABLE WHERE PROJECTID=''", objConn, objTrans);
cmd.CommandType = CommandType.Text;
var dataTable = new DataTable("SomeTableName");
using (var adapter = new SqlDataAdapter(cmd))
{
var dt = adapter.Fill(dataTable); // Exception happens here
}
objTrans.Commit(); // Commit here
}
catch (Exception ex)
{
errorInformation.Add(ex.Message);
}
var sql1 = $"insert into tblProject values('8', 'TestProject')";
SqlCommand objCmd2 = new SqlCommand(sql1, objConn, objTrans);
objCmd2.ExecuteNonQuery();
if (errorInformation.Any())
{
objTrans.Rollback(); // Rollback here
}
}
The query that gets executed after the exception, using the same connection object will not rollback. This is a bug that Microsoft needs to look into. Otherwise their rollback feature is not reliable.
I would expect either my second insert command to fail or my rollback to be successful.

Cyrillic value insert error in SqlParameter on mono

Next code snippet throws exception if I use as value in #Name string with cyrillic characters. If I use latin chars it works fine. On Windows host with .Net 4.0 works fine. But on Ubuntu 14.04 with last mono it has error. SQL server MS SQL 2014.
StringBuilder sb = new StringBuilder();
sb.AppendLine("INSERT INTO [MyTable]([Name],[ID]) ");
sb.AppendLine("VALUES(");
sb.Append("#Name, ");
sb.Append("#ID)");
SqlConnection sqlConnection =
new SqlConnection(connStr);
try
{
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand(sb.ToString(), sqlConnection);
SqlParameter sqlParameter = null;
var msg = "Имя";
sqlParameter = new SqlParameter("#Name", SqlDbType.VarChar, 0, "Name");
sqlParameter.Value = msg;
sqlCommand.Parameters.Add(sqlParameter);
sqlParameter = new SqlParameter("#ID", SqlDbType.BigInt, 0, "ID");
sqlParameter.Value = 39;
sqlCommand.Parameters.Add(sqlParameter);
sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
var a = 0;
}
finally
{
sqlConnection.Close();
}
Try
sqlParameter = new SqlParameter("#Name", SqlDbType.NVarChar, 0, "Name");
instead of
sqlParameter = new SqlParameter("#Name", SqlDbType.VarChar, 0, "Name");

Retrieve mssql primary key from query?

In C# Visual Studio Express Windows Forms:
How do I retrieve the primary key of a just executed insert query.
Here is my con+query code:
SqlConnection con = new SqlConnection(...);
SqlCommand command = con.CreateCommand();
command.CommandText = "INSERT INTO bestillinger (ha) VALUES (#ha);
command.Parameters.AddWithValue("#ha", listBox1.SelectedItem.ToString());
con.Open();
command.ExecuteNonQuery();
con.Close();
With a manual Close(), you risk leaking a connection if the code that uses it throws an exception. So please use using instead.
Assuming your PK is an identity column, the new value is most easily retrieved with scope_identity():
using (var con = new SqlConnection(...))
{
con.Open();
var command = con.CreateCommand();
command.CommandText = #"
INSERT INTO bestillinger (ha) VALUES (#ha);
select scope_identity();";
command.Parameters.AddWithValue("#ha", listBox1.SelectedItem.ToString());
var newPk = (long) command.ExecuteScalar();
}
As #Andomar said in his answer, ensure you properly close the connection.
Another way to return the value of the newly inserted identity field would be:
using (var con = new SqlConnection(...))
{
con.Open();
var command = con.CreateCommand();
command.CommandText = #"
INSERT INTO bestillinger (ha) OUTPUT inserted.[ID] VALUES (#ha);";
command.Parameters.AddWithValue("#ha", listBox1.SelectedItem.ToString());
var newPk = (long) command.ExecuteScalar();
}
[ID] would be replaced with the name of the identity field (or any field, or fields) that you want.

Pass parameters to stored procedure

My stored procedures declaration looks like this:
alter procedure [dbo].[usp_A_MySproc]
#aID int,
#bID int,
#cID int
My code in application layer:
using (var transaction = Session.Transaction)
{
try
{
transaction.Begin();
Session.CreateSQLQuery("exec usp_A_MySproc ?, ?, ?")
.SetParameter("aID", 1)
.SetParameter("bID", 2)
.SetParameter("cID", 3);
transaction.Commit();;
}
}
Exception: "could not locate named parameter [aID]"
Can you see something wrong?
Thank you!
For nhibernate
Session.CreateSQLQuery("exec usp_A_MySproc #aID = 1, #bID =2, #cID = 3")
or
IQuery query = Session.CreateSQLQuery("exec usp_A_MySproc #aID =:aID, #bID =:bID , #cID =:cID");
query.SetInt32("aID",1);
query.SetInt32("bID",2);
query.SetInt32("cID",3);
query.ExecuteUpdate();
or to match what you were doing
Session.CreateSQLQuery("exec usp_A_MySproc #aID =:aID, #bID =:bID , #cID =:cID")
.SetParameter("aID", 1)
.SetParameter("bID", 2)
.SetParameter("cID", 3);
For use of SqlCommand modify the code to the following, connectionString stands for your connection string
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("usp_A_MySproc ", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#aID", SqlDbType.Int32).Value = 1;
cmd.Parameters.Add("#bID", SqlDbType.Int32).Value = 2;
cmd.Parameters.Add("#cID", SqlDbType.Int32).Value = 3;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
or
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("usp_A_MySproc ", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#aID", 1) ;
cmd.Parameters.AddWithValue("#bID", 2) ;
cmd.Parameters.AddWithValue("#cID", 3) ;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
refer to MSDN article on SQLCommand how to properly add parameters
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx
You need to set the parameters by position:
using (var transaction = Session.BeginTransaction())
{
Session.CreateSQLQuery("exec usp_A_MySproc ?, ?, ?")
.SetInt32(0, aIDValue)
.SetInt32(1, bIDValue)
.SetInt32(2, cIDValue)
.ExecuteUpdate();
transaction.Commit();
}

Couldn't fetch return value (0 or 1) from stored procedure.?

I am returning 0 and 1 from a stored procedure like following. How can I fetch it in c# asp.net file?
ALTER procedure [dbo].[crudprocedure]
#getusername varchar(20),
#getfirstname varchar(20),
#getlastname varchar(20),
#getaddress varchar(20)
as
begin
IF not exists (select username from crudtable where username=#getusername)
begin
insert into crudtable(username,firstname,lastname,address)
values (#getusername,#getfirstname,#getlastname,#getaddress)
return 0
end
else
return 1
end
If you're using SQL Server - then try this code here:
using (SqlConnection conn = new SqlConnection("...put your connection string here..."))
using (SqlCommand cmd = new SqlCommand("dbo.crudprocedure", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#getusername", SqlDbType.VarChar, 20).Value = "test";
cmd.Parameters.Add("#getfirstname", SqlDbType.VarChar, 20).Value = "test";
cmd.Parameters.Add("#getlastname", SqlDbType.VarChar, 20).Value = "test";
cmd.Parameters.Add("#getaddress", SqlDbType.VarChar, 20).Value = "test";
// define additional paramter of Direction = ReturnValue
cmd.Parameters.Add("RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
// open connection, execute stored proc, close connection
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
// fetch the value of the "ReturnValue" parameter
int returnValueInt = Convert.ToInt32(cmd.Parameters["RETURN_VALUE"].Value);
}
Basically, since you're sending back that value using RETURN 1 from the stored procedure, you need to add an additional parameter to your SqlCommand object that has a .Direction of ParameterDirection.ReturnValue.
That parameter will be set to the value that you send back from the stored procedure using RETURN ....

Resources