call a stored procedure that takes in string values name, address and outputs a unique id in csharp

You can call a stored procedure that takes string values as input and outputs a unique id in C# using the following code snippet:

main.cs
using System.Data.SqlClient;  // Required for using SQL client classes

class Program {
    static void Main(string[] args) {
        // Connect to SQL Server instance
        SqlConnection conn = new SqlConnection("<your_connection_string>");
        conn.Open();  // Open the connection to the SQL Server

        // Create a new SQL command object
        SqlCommand cmd = new SqlCommand("sp_create_new_customer", conn);
        cmd.CommandType = CommandType.StoredProcedure;

        // Add input parameters to the command object
        cmd.Parameters.Add(new SqlParameter("@name", "John Doe"));
        cmd.Parameters.Add(new SqlParameter("@address", "123 Main St, Anytown USA"));

        // Add output parameter to the command object
        SqlParameter outputParam = new SqlParameter("@customer_id", SqlDbType.Int);
        outputParam.Direction = ParameterDirection.Output;  // Specify direction as output
        cmd.Parameters.Add(outputParam);

        // Execute the stored procedure and get the output value
        cmd.ExecuteNonQuery();  // Execute the stored proc
        int id = Convert.ToInt32(outputParam.Value);  // Get the value of the output parameter

        // Close the SQL connection
        conn.Close();
    }
}
1245 chars
30 lines

In the above code, the SqlConnection class is used to connect to the SQL Server instance. The SqlCommand object is created with the stored procedure name and the SqlConnection object.

Input parameters are added to the command object using the SqlParameter class. An output parameter is also added to the command object using the same class, but its Direction property is set to ParameterDirection.Output.

Finally, the ExecuteNonQuery() method is called on the SqlCommand object to execute the stored procedure. After execution, the value of the output parameter is obtained using the Value property of the outputParam object.

gistlibby LogSnag