Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a parameter to an sql stored procedure in c#

        string commandGetIslemIdleri = ("EXEC GetIslemIdleri");

        cmd = new SqlCommand(commandGetIslemIdleri, sqlConn);
        cmd.Parameters.Add(new SqlParameter("@CARIID", 110));

        using (var reader = cmd.ExecuteReader()) //error occurs here
        {
            while (reader.Read())
            {
                islemidleri.Add(reader.GetInt32(0));

            }

        }

Above is the code i am trying to write to call the below stored procedure with a parameter CARIID which is an integer. when i run the code an error occurs and says "Procedure or function 'GetIslemIdleri' expects parameter '@CARIID', which was not supplied." but as much as i understand from the examples i read from here i am sending the parameter with this code cmd.Parameters.Add(new SqlParameter("@CARIID", 110)); i need help, thank you in advance.

ALTER PROCEDURE [dbo].[GetIslemIdleri] 
    @CARIID int 
AS
BEGIN
SET NOCOUNT ON;

SELECT ID
FROM TBLP1ISLEM
WHERE TBLP1ISLEM.CARI_ID=@CARIID
END
like image 204
Bastardo Avatar asked Mar 23 '11 15:03

Bastardo


2 Answers

If you want to call a stored procedure using a SqlCommand, do not execute EXEC GetIslemIdleri, execute just GetIslemIdleri, setting CommandType to CommandType.StoredProcedure:

cmd = new SqlCommand("GetIslemIdleri", sqlConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@CARIID", 110));

using (var reader = cmd.ExecuteReader()) //error occurs here
{
    while (reader.Read())
    {
        islemidleri.Add(reader.GetInt32(0));
    }
}
like image 111
Mormegil Avatar answered Nov 17 '22 00:11

Mormegil


you forgot to add the prodecure`s name:

cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetIslemIdleri";
cmd.Parameters.Add("@CARIID", SqlDBType.Int).Value = 110;

And do procedure as:

CREATE PROCEDURE [dbo].[GetIslemIdleri] 
(
    @CARIID int 
)
AS
BEGIN
SET NOCOUNT ON;    
SELECT ID FROM TBLP1ISLEM WHERE TBLP1ISLEM.CARI_ID = @CARIID
END

This has to work.

like image 3
Mitja Bonca Avatar answered Nov 17 '22 01:11

Mitja Bonca