Search

Index

Revindex Task Scheduler

Execute stored procedure (Razor C#)

Last updated on 2015-03-25 1 mins. to read

This example shows how to execute a stored procedure from Razor (C#).


@{
 // Assumption, the SiteSqlServer connection string is in the web.config file
 // Replace "SiteSqlServer" with the actual database name

 // Replace "120" with the actual Command Timeout required (in seconds)
 // Replace "SPName" with the actual stored procedure name

 // Replace "@Parm1, @Parm2" with the actual parameter name
 // -----------------------------------------------------------------------

 var connString = DotNetNuke.Common.Utilities.Config.GetConnectionString("SiteSqlServer");
 var connection = new System.Data.SqlClient.SqlConnection(connString);

 var cmdString = "DBName.dbo.SPName";
 var cmdTimeout = 120;

 var cmd = new System.Data.SqlClient.SqlCommand();
 cmd.CommandType = System.Data.CommandType.StoredProcedure;
 cmd.CommandText = cmdString;
 cmd.CommandTimeout = cmdTimeout;
 cmd.Connection = connection;

 cmd.Parameters.Add("@Parm1", System.Data.SqlDbType.Int);
 cmd.Parameters["@Parm1"].Direction = System.Data.ParameterDirection.Input;
 cmd.Parameters["@Parm1"].Value = 1;

 cmd.Parameters.Add("@Parm2", System.Data.SqlDbType.Int);
 cmd.Parameters["@Parm2"].Direction = System.Data.ParameterDirection.Input;
 cmd.Parameters["@Parm2"].Value = 2;

 connection.Open();
 cmd.ExecuteNonQuery();
 connection.Close();
}

Comments

Max Nov 23, 2016 11:36 AM
Thank you so much for this!! Been looking at different solutions and they were all either too complex or not working for me. Perfect :)

Powered by Revindex Wiki