Executing a SQL Server stored procedure in C#
Are you kidding me? I’m a major amatuer at anything .NET, and after some Googling and about 15 minutes of coding, this works. How ridiculously easy.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ExecuteStoredProcedure
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn;
try
{
conn = new SqlConnection("server=server;database=db;Trusted_Connection=yes");
conn.Open();
Console.WriteLine("Connection successful…");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
SqlCommand db_cmd = new SqlCommand("dbo.usp_c_sharp_test",conn);
db_cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader data_reader;
data_reader = db_cmd.ExecuteReader();
data_reader.Close();
conn.Close();
}
}
}
Download this code: execute-stored-procedure.cs


