Search code examples
c#sql-serverstored-proceduresado.net

C# program does not execute Stored Procedure


I want to run my Stored Procedure on an Azure SQL-Server from C# but it does not work and I do not know how to find out why. The stored procedure has two input parameters and based on these insert information into a table. So I can see in the table if there is a new entry or not (SP worked or not).

Using my SP in the SQL-Server as

exec Commentary.Add_Information @ID = 34926, @year = '2020'  

works absolutely fine. But executing it from c# does not make an entry in the table

public void CreateBasicInformation()
{
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
    builder.DataSource = "myServer.database.windows.net";
    builder.UserID = "admin";
    builder.Password = "myPass";
    builder.InitialCatalog = "myDB";

    try
    {
        SqlConnection cn = new SqlConnection(builder.ConnectionString);
        cn.Open();
        SqlCommand cmd = new SqlCommand("Add_Information", cn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@ID", "34926");
        cmd.Parameters.AddWithValue("@year", "2020");
        cn.Close();
    }
    catch (SqlException sqlEx)
    {
        Console.WriteLine(sqlEx.Message);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

I already tried to catch an error but there is none. All I get at the end is

The program '[9480] test_SP.exe' has exited with code 0 (0x0).

Is there a mistake in the code or is there a way I can find out why C# and the SP are not working together?


Solution

  • You didn't actually execute your command, you need to add the following line to execute it:

    cmd.ExecuteNonQuery();
    cn.Close();
    

    It is also highly recommended to use the Using statement nowadays:

    The purpose of the using statement is to provide a simpler way to specify when the unmanaged resource is needed by your program, and when it is no longer needed.