views:

5238

answers:

4

Hi

i want to execute this StoredProcedure from c# program How can i do this using c#

Any Help is Greatly Apreciated

I have written the following stored procedure in sqlserver query window and saved it as stored1

 use master 
 go
 create procedure dbo.test as

 DECLARE @command as varchar(1000), @i int
 SET @i = 0
 WHILE @i < 5
 BEGIN
 Print 'I VALUE ' +CONVERT(varchar(20),@i)
 EXEC(@command)
 SET @i = @i + 1
 END

EDITED:

   using System;
   using System.Collections.Generic;
   using System.Text;
   using System.Data;
   using System.Data.SqlClient;
   namespace AutomationApp
   {
    class Program
     {
      public void RunStoredProc()
  {
 SqlConnection conn = null;
 SqlDataReader rdr  = null;

 Console.WriteLine("\nTop 10 Most Expensive Products:\n");

 try
 {

 conn = new SqlConnection("Server=(local);DataBase=master;Integrated Security=SSPI");
 conn.Open();
 SqlCommand cmd  = new SqlCommand("dbo.test", conn);
 cmd.CommandType = CommandType.StoredProcedure;
 rdr = cmd.ExecuteReader();
  /*while (rdr.Read())
  {
   Console.WriteLine(
    "Product: {0,-25} Price: ${1,6:####.00}",
    rdr["TenMostExpensiveProducts"],
    rdr["UnitPrice"]);
  }*/
 }
 finally
 {
  if (conn != null)
  {
   conn.Close();
  }
  if (rdr != null)
  {
   rdr.Close();
  }
 }
          }
          static void Main(string[] args)
        {
          Console.WriteLine("Hello World");
          Program p= new Program();
          p.RunStoredProc();     
          Console.Read();
        }

     }
  }

Then it display the exception can not find the stored procedure dbo.test .can i need to give the path?? if yes in which location the stored [procedures wil stored.

Help me in this regard

+2  A: 
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) { 
                           CommandType = CommandType.StoredProcedure }) {
   conn.Open();
   command.ExecuteNonQuery();
   conn.Close();
}
Mehrdad Afshari
+3  A: 
using (SqlConnection sqlConnection1 = new SqlConnection("Your Connection String")) {
using (SqlCommand cmd = new SqlCommand()) {
  Int32 rowsAffected;

  cmd.CommandText = "StoredProcedureName";
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.Connection = sqlConnection1;

  sqlConnection1.Open();

  rowsAffected = cmd.ExecuteNonQuery();

}}
BlackTigerX
I am worried about how the cmd.CommandText = "Stored1" interpretes my stored procedure.I dont know.
Cute
The "CommandText" must be set to the NAME of the stored procedure, which is then executed from C# as if you had executed "exec StoredProcedureName" in SSMS - or what are you worried about?
marc_s
How can i give the storedprocedure name for the above stored procedurecan u plz tell me??
Cute
Can i give the stored procedure name in SSMS or else??
Cute
so, first, you would have to create the stored procedure, in the case of the code you have, you would need to add: "create procedure dbo.NameOfYourStoredProcedureHere as" at the beginning
BlackTigerX
@Cute: if you have this as a stored procedure, you **MUST** have a name! The name used in the "CREATE PROCEDURE (procedurename)" call. If you do not have that, then you do not have a stored procedure (but just a batch of T-SQL statements) and then you cannot use the "CommandType = StoredProcedure", obviusly
marc_s
i have edited the post with code.Now i am facing a problem that it rises the exception the stored procedure dbo.test not found when i try to debug the program
Cute
Your stored procedure is not returning anything - use .ExecuteNonQuery() (as the answer here says) instead of .ExecuteReader()
marc_s
and you might want to save your self some typing and potential errors, use *using* instead of try..finally
BlackTigerX
+1  A: 
SqlConnection conn = null;
SqlDataReader rdr  = null;
conn = new 
       SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
      conn.Open();

      // 1.  create a command object identifying
      //     the stored procedure
      SqlCommand cmd  = new SqlCommand(
       "CustOrderHist", conn);

      // 2. set the command object so it knows
      //    to execute a stored procedure
      cmd.CommandType = CommandType.StoredProcedure;

      // 3. add parameter to command, which
      //    will be passed to the stored procedure
      cmd.Parameters.Add(
       new SqlParameter("@CustomerID", custId));

      // execute the command
      rdr = cmd.ExecuteReader();

      // iterate through results, printing each to console
      while (rdr.Read())
      {
       Console.WriteLine(
        "Product: {0,-35} Total: {1,2}",
        rdr["ProductName"],
        rdr["Total"]);
      }

Here are some interisting links you could read:

http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx
http://www.c-sharpcorner.com/UploadFile/dclark/InsOutsinCS11302005072332AM/InsOutsinCS.aspx
http://www.codeproject.com/KB/cs/simplecodeasp.aspx
http://msdn.microsoft.com/en-us/library/ms171921(VS.80).aspx
Bhaskar
A: 

You mean that your code is DDL? If so, MSSQL has no difference. Above examples well shows how to invoke this. Just ensure

CommandType = CommandType.Text
Dewfy