-2

So currently I'm trying to wrap my head around the concept of Stored Procedures, specifically in SQL. I'm working with Microsoft SQL Server Manager Studio and already tried some basic Stored Procedures, i also found a way to execute a Stored Procedure from C# code. But: Is it possible to call a stored Procedure from C#, give it specific variables as parameters as if it were a method and let the Procedure write those variables into columns (aka use them in an INSERT INTO)? Is that possible?

Mondblut
  • 199
  • 1
  • 14
  • google is your friend [See here](https://www.mssqltips.com/sqlservertutorial/2519/insert-stored-procedure-in-sql-server/) – BugFinder Apr 10 '18 at 11:16
  • But that only explains how the Procedure is implemented on the SQL server... How do i call the Procedure from C# code and give it parameters, like the names of customers. – Mondblut Apr 10 '18 at 11:19
  • https://stackoverflow.com/questions/1260952/how-to-execute-a-stored-procedure-within-c-sharp-program#1260961 – andreasnico Apr 10 '18 at 11:22
  • the same way you add parameters to everything else :) (See @andreasnico's comment) – BugFinder Apr 10 '18 at 11:33

1 Answers1

-2

To your program a stored procedure is just another object on your database such as a table or view. There is not much difference in how they are called.

Stored procedure example:

    connection = new SqlConnection
            {
                ConnectionString = ConfigurationManager.ConnectionStrings[DatabaseConnectionName].ConnectionString
            };
            connection.Open();
            //storedProcedureName is from your database
            command = new SqlCommand(@"[dbo].[storedProcedureName]", connection)                
            {
                CommandType = CommandType.StoredProcedure
            };
            //passing a parameter to the stored procedure
            command.Parameters.AddWithValue("@StudyID", khStudyId);

            reader = command.ExecuteReader();

Calling SQL from code:

onnection = new SqlConnection(ConfigurationManager.ConnectionStrings[DatabaseConnectionName].ConnectionString);
            connection.Open();

            command = new SqlCommand(@"[dbo].[UserInformation]", connection)
            {
                CommandType = CommandType.Text
            };
            command.Parameters.AddWithValue("@StudyName", sponsorName);
            command.CommandText = @"select ID from [dbo].[Sponsors] where [Name] = @StudyName";

            reader = command.ExecuteReader();

            if (reader != null)
            {
                if (reader.Read())
                {
                    output = Convert.ToInt32(reader["ID"]);
                }
            }
JazzmanJim
  • 97
  • 1
  • 5