2009-08-11 33 views
190

Tôi muốn thực hiện quy trình được lưu trữ này từ chương trình C#.Cách thực hiện một thủ tục lưu sẵn trong chương trình C#

Tôi đã viết các thủ tục lưu trữ sau đây trong một cửa sổ truy vấn SQLServer và lưu nó như 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(); 
     } 
    } 
} 

này hiển thị ngoại lệ Cannot find the stored procedure dbo.test. Tôi có cần cung cấp đường dẫn không? Nếu có, trong đó vị trí nên lưu trữ các thủ tục được lưu trữ?

+2

Bạn nên sử dụng cơ sở dữ liệu không phải là chính ngay cả khi thử nghiệm. Đây là một cơ sở dữ liệu hệ thống và cuối cùng bạn sẽ gây ra vấn đề.Trong SQL 2012 nó sẽ không cho phép tôi tạo một bảng ở đó. Nó sẽ ngược lại cho phép tôi tạo ra một sproc. :/ –

+0

Câu trả lời bất kể: bạn đã kiểm tra xem sp của bạn có thực sự được tạo với tên bạn đã cung cấp (dbo.test) không? Tôi không biết điều gì sẽ xảy ra nếu một người dùng không dbo cố gắng tạo dbo.test ... nó có được tạo ra như non-dbo.test không? – DigCamara

+0

có thể trùng lặp của [Gọi một thủ tục được lưu trữ với tham số trong C#] (http://stackoverflow.com/questions/7542517/call-a-stored-procedure-with-parameter-in-c-sharp) – obayhan

Trả lời

265
using (var conn = new SqlConnection(connectionString)) 
using (var command = new SqlCommand("ProcedureName", conn) { 
          CommandType = CommandType.StoredProcedure }) { 
    conn.Open(); 
    command.ExecuteNonQuery(); 
} 
+43

Bạn thậm chí có thể loại bỏ 'conn.Close', được ngụ ý bởi' Dispose' –

+14

Điều đó đúng cho trường hợp này. Tôi thích kết hợp các lệnh gọi 'Open' và' Close'. Nếu bạn nói, cấu trúc lại đối tượng kết nối ra ngoài như một trường trong tương lai và loại bỏ câu lệnh using, bạn có thể vô tình quên thêm 'Close' và kết thúc bằng một kết nối mở. –

+7

Bạn sẽ làm như thế nào nếu tham số proc được lưu trữ cần thiết? chỉ cần thêm các tham số cho đối tượng lệnh có cùng tên và loại? – Dani

18
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(); 

}} 
+0

Tôi lo lắng về cách cmd.CommandText = "Stored1" giải thích thủ tục đã lưu trữ của tôi. Tôi không biết. – Cute

+2

"CommandText" phải được đặt thành NAME của thủ tục được lưu trữ, sau đó được thực hiện từ C# như thể bạn đã thực thi "exec StoredProcedureName" trong SSMS - hoặc bạn đang lo lắng về điều gì? –

+0

Làm cách nào tôi có thể cung cấp tên được lưu trữ cho quy trình được lưu trữ ở trên u có thể cho tôi biết không ?? – Cute

183
using (SqlConnection 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 
    using (SqlDataReader 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"]); 
     } 
    } 
} 

Dưới đây là một số liên kết thú vị bạn có thể đọc:

+23

Bạn thực sự nên sử dụng từ khóa "using" . Đẩy mở/đóng trách nhiệm với khung công tác. – TruMan1

1

Bạn có nghĩa là mã của bạn là DDL? Nếu có, MSSQL không có sự khác biệt. Các ví dụ trên cũng cho thấy cách gọi điều này. Chỉ cần đảm bảo

CommandType = CommandType.Text 
13
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"]); 
} 
14

Calling Thủ tục Store trong C#

SqlCommand cmd = new SqlCommand("StoreProcedureName",con); 
cmd.CommandType=CommandType.StoredProcedure; 
cmd.Parameters.AddWithValue("@value",txtValue.Text); 
int rowAffected=cmd.ExecuteNonQuery(); 
1

Không Dapper trả lời ở đây. Vì vậy, tôi đã thêm một

using Dapper; 
using System.Data.SqlClient; 

using (var cn = new SqlConnection(@"Server=(local);DataBase=master;Integrated Security=SSPI")) 
    cn.Execute("dbo.test", commandType: CommandType.StoredProcedure); 
3

Bằng cách sử dụng Ado.net

using System; 
using System.Data; 
using System.Data.SqlClient; 
using System.Configuration; 

namespace PBDataAccess 
{ 
    public class AddContact 
    { 
     // for preparing connection to sql server database 

     private SqlConnection conn; 

     // for preparing sql statement or stored procedure that 
     // we want to execute on database server 

     private SqlCommand cmd; 

     // used for storing the result in datatable, basically 
     // dataset is collection of datatable 

     private DataSet ds; 

     // datatable just for storing single table 

     private DataTable dt; 

     // data adapter we use it to manage the flow of data 
     // from sql server to dataset and after fill the data 
     // inside dataset using fill() method 

     private SqlDataAdapter da; 


     // created a method, which will return the dataset 

     public DataSet GetAllContactType() 
     { 



    // retrieving the connection string from web.config, which will 
    // tell where our database is located and on which database we want 
    // to perform opearation, in this case we are working on stored 
    // procedure so you might have created it somewhere in your database. 
    // connection string will include the name of the datasource, your 
    // database name, user name and password. 

     using (conn = new SqlConnection(ConfigurationManager.ConnectionString["conn"] 
     .ConnectionString)) 

       { 
        // Addcontact is the name of the stored procedure 
        using (cmd = new SqlCommand("Addcontact", conn)) 

        { 
         cmd.CommandType = CommandType.StoredProcedure; 

        // here we are passing the parameters that 
        // Addcontact stored procedure expect. 
        cmd.Parameters.Add("@CommandType", 
        SqlDbType.VarChar, 50).Value = "GetAllContactType"; 

         // here created the instance of SqlDataAdapter 
         // class and passed cmd object in it 
         da = new SqlDataAdapter(cmd); 

         // created the dataset object 
         ds = new DataSet(); 

         // fill the dataset and your result will be 
         stored in dataset 
         da.Fill(ds); 
        }      
      } 
      return ds; 
     } 
} 

****** Stored Procedure ****** 

CREATE PROCEDURE Addcontact 
@CommandType VARCHAR(MAX) = NULL 
AS 
BEGIN 
    IF (@CommandType = 'GetAllContactType') 
    BEGIN 
    SELECT * FROM Contacts 
    END 
END 
+0

Dòng nhận xét của bạn bị hỏng, cũng nếu bạn có thể cung cấp cho thủ tục lưu trữ trong nhận xét của bạn sẽ tốt cho chúng tôi. – PeerNet

+0

đã thêm quy trình được lưu trữ trong mã, hãy kiểm tra. – Johnny

1

Hãy kiểm SprocMapper (i là tác giả)

https://www.nuget.org/packages/SprocMapper/

SqlServerAccess sqlAccess = new SqlServerAccess("your connection string"); 
var result = sqlAccess.Procedure().ExecuteNonQuery("StoreProcedureName"); 

Cũng có một một loạt các tính năng khác mà bạn có thể thích.

1

đây là một ví dụ về một thủ tục lưu trữ mà trả về giá trị và nó thực hiện trong C#

CREATE PROCEDURE [dbo].[InsertPerson] 
-- Add the parameters for the stored procedure here 
@FirstName nvarchar(50),@LastName nvarchar(50), 
@PersonID int output 
AS 
BEGIN 
    insert [dbo].[Person](LastName,FirstName) Values(@LastName,@FirstName) 

    set @PersonID=SCOPE_IDENTITY() 
END 
Go 


-------------- 
// Using stored procedure in adapter to insert new rows and update the identity value. 
    static void InsertPersonInAdapter(String connectionString, String firstName, String lastName) { 
     String commandText = "dbo.InsertPerson"; 
     using (SqlConnection conn = new SqlConnection(connectionString)) { 
     SqlDataAdapter mySchool = new SqlDataAdapter("Select PersonID,FirstName,LastName from [dbo].[Person]", conn); 

     mySchool.InsertCommand = new SqlCommand(commandText, conn); 
     mySchool.InsertCommand.CommandType = CommandType.StoredProcedure; 

     mySchool.InsertCommand.Parameters.Add( 
      new SqlParameter("@FirstName", SqlDbType.NVarChar, 50, "FirstName")); 
     mySchool.InsertCommand.Parameters.Add( 
      new SqlParameter("@LastName", SqlDbType.NVarChar, 50, "LastName")); 

     SqlParameter personId = mySchool.InsertCommand.Parameters.Add(new SqlParameter("@PersonID", SqlDbType.Int, 0, "PersonID")); 
     personId.Direction = ParameterDirection.Output; 

     DataTable persons = new DataTable(); 
     mySchool.Fill(persons); 

     DataRow newPerson = persons.NewRow(); 
     newPerson["FirstName"] = firstName; 
     newPerson["LastName"] = lastName; 
     persons.Rows.Add(newPerson); 

     mySchool.Update(persons); 
     Console.WriteLine("Show all persons:"); 
     ShowDataTable(persons, 14); 
3

Đây là mã để thực hiện các thủ tục lưu trữ với và với các thông số ra. Lưu ý rằng tên thuộc tính của đối tượng cần phải khớp với các tham số của thủ tục đã lưu.

private static string ConnString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString; 
    private SqlConnection Conn = new SqlConnection(ConnString); 

    public void ExecuteStoredProcedure(string procedureName) 
    { 
     SqlConnection sqlConnObj = new SqlConnection(ConnString); 

     SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj); 
     sqlCmd.CommandType = CommandType.StoredProcedure; 

     sqlConnObj.Open(); 
     sqlCmd.ExecuteNonQuery(); 
     sqlConnObj.Close(); 
    } 

    public void ExecuteStoredProcedure(string procedureName, object model) 
    { 
     var parameters = GenerateSQLParameters(model); 
     SqlConnection sqlConnObj = new SqlConnection(ConnString); 

     SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj); 
     sqlCmd.CommandType = CommandType.StoredProcedure; 

     foreach (var param in parameters) 
     { 
      sqlCmd.Parameters.Add(param); 
     } 

     sqlConnObj.Open(); 
     sqlCmd.ExecuteNonQuery(); 
     sqlConnObj.Close(); 
    } 

    private List<SqlParameter> GenerateSQLParameters(object model) 
    { 
     var paramList = new List<SqlParameter>(); 
     Type modelType = model.GetType(); 
     var properties = modelType.GetProperties(); 
     foreach (var property in properties) 
     { 
      if (property.GetValue(model) == null) 
      { 
       paramList.Add(new SqlParameter(property.Name, DBNull.Value)); 
      } 
      else 
      { 
       paramList.Add(new SqlParameter(property.Name, property.GetValue(model))); 
      } 
     } 
     return paramList; 

    } 
Các vấn đề liên quan