SQL Server中預存程序Stored Procedure建立及C#調用,

來源:互聯網
上載者:User

SQL Server中預存程序Stored Procedure建立及C#調用,

預存程序就是已經編譯好的、最佳化過的放在資料庫伺服器中的一些SQL語句;可供應用程式直接調用。使用預存程序有以下幾個優點:
1、執行速度比普通的SQL語句快
2、便於集中控制
3、可以降低網路的通訊量
4、保證資料庫的安全性和完整性
5、靈活性

建立預存程序
可以採用Transact-SQL語句來建立預存程序Stored Procedured。在Microsoft SQL Server Management Studio中Databases->Database Name->Programmability->Stored Procedures右鍵選擇Stored Procedure就產生了一個建立預存程序的模板,修改其中的內容再執行就建立了Stored Procedured。

下面我首先以建立對錶中插入資料的預存程序來為例。比如我的原始表是如下語句所建立的:

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'Persons') AND OBJECTPROPERTY(id,N'isUserTable') = 1) CREATE TABLE Persons (Id_P int,LastName varchar(255),FirstName varchar(255),Address varchar(255),City varchar(255))

Stored Procedure建立插入功能的SQL如下:

USE [databasename]GO/****** Object:  StoredProcedure [dbo].[insert_persions]    Script Date: 2/25/2015 11:14:11 AM ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOIF OBJECT_ID ('insert_persons','p') IS NOT NULL    DROP PROCEDURE insert_persons;GO-- =============================================-- Author:      <Author,,Name>-- Create date: <Create Date,,>-- Description: <Description,,>-- =============================================CREATE PROCEDURE insert_persons    -- Add the parameters for the stored procedure here    @id int,     @lastname varchar(255),    @firstname varchar(255),    @adress varchar(255),    @city varchar(255)ASBEGIN    -- SET NOCOUNT ON added to prevent extra result sets from    -- interfering with SELECT statements.    SET NOCOUNT ON;    -- Insert statements for procedure here    INSERT Persons (Id_P, LastName, FirstName, Address, City)    VALUES (@id, @lastname, @firstname, @adress, @city)ENDGO

以上程式碼完成了首先檢查Stored Procedure是否存在,如果存在先把該Stored Procedure刪掉,然後再建立該Stored Procedure。而其功能則是通過傳入的參數,插入一條記錄。直接點擊Execute或者按F5則以上代碼被執行,相應的資料庫下面將有一個Stored Procedure名字為insert_persons。以SQL Server 2014為例,只要重新整理相應的資料庫,再到Programmability->Stored Procedures下面就發現多了個dbo.insert_persons。

執行預存程序
在Stored Procedures下面找到相應的預存程序,點擊右鍵選擇Execute Stored Procedure…就可以產生一個新的對話方塊,填寫輸入的參數再點擊OK就執行完畢。回去查看相應的表會發現多了一行資料。

當然我們也可以通過SQL語句來執行預存程序。

EXECUTE insert_persons 5,"Wang","San","Zhongguancun","Beijing"EXECUTE insert_persons @id = 6,@firstname = "Wang",@lastname = "San",@adress = "Zhongguancun",@city = "Beijing"

C#執行預存程序
下面的代碼比較簡單的展示了如何利用C#來執行上面建立的預存程序:

            String conStr = @"Data Source=host\SQLEXPRESS;Initial Catalog=dbtan;Integrated Security=SSPI";            SqlConnection con = new SqlConnection(conStr);            try            {                con.Open();                Console.WriteLine("Connect Sucess!");                SqlCommand com = new SqlCommand();                com.CommandType = System.Data.CommandType.StoredProcedure;                com.Connection = con;                com.CommandText = "insert_persons";                SqlParameter pId = new SqlParameter("id", 10);                SqlParameter pLastName = new SqlParameter("lastname", "last");                SqlParameter pFirstName = new SqlParameter("firstname", "first");                SqlParameter pAdress = new SqlParameter("adress", "pop");                SqlParameter pCity = new SqlParameter("city", "Hangzhou");                com.Parameters.Add(pId);                com.Parameters.Add(pLastName);                com.Parameters.Add(pFirstName);                com.Parameters.Add(pAdress);                com.Parameters.Add(pCity);                com.ExecuteNonQuery();            }            catch (Exception e)            {                Console.WriteLine(e.ToString());            }            finally            {                con.Close();            }            Console.ReadKey();

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.