ASP.NET中如何調用預存程序

來源:互聯網
上載者:User

  用ASP.NET與SQL SERVER可是緣份最好了,稍大的程式一般第一先考慮的是SQL SERVER,只是一些很考慮經濟的才使用ACCESS等了。用SQL SERVER,為了使資料庫的效率更好,一般都會才取預存程序,因預存程序執行速度快,並且可以實現一些進階的查詢等功能。比如傳入一些資料參數,但執行的SQL過程可能不同等。

  下面就來個例子,建立一新的角色,要求角色的名字不能重複,以下是一預存程序。

  

CREATE PROCEDURE sp_AccountRole_Create

@CategoryID int,
@RoleName nvarchar(10),
@Description nvarchar(50),
@RoleID int output
AS
DECLARE @Count int

-- 尋找是否有相同名稱的記錄
SELECT @Count = Count(RoleID) FROM Account_Role WHERE
RoleName = @RoleName

IF @Count = 0

INSERT INTO Account_Role
(CategoryID, RoleName, Description) valueS
(@CategoryID, @RoleName, @Description)

SET @RoleID = @@IDENTITY

RETURN 1
GO

  
  執行預存程序的C#過程:

  

SqlConnection DbConnection = new SqlConnection(mConnectionString);
SqlCommand command = new SqlCommand( "sp_AccountRole_Create", DbConnection );
DbConnection.Open(connectString);
// 廢置SqlCommand的屬性為預存程序
command.CommandType = CommandType.StoredProcedure;

command.Parameters.Add("@CategoryID", SqlDbType.Int, 4);
command.Parameters.Add("@RoleName", SqlDbType.NVarChar, 10);
command.Parameters.Add("@Description", SqlDbType.NVarChar, 50);
command.Parameters.Add("@RoleID", SqlDbType.Int, 4);
// 傳回值
command.Parameters.Add("Returnvalue",
SqlDbType.Int,
4, // Size
ParameterDirection.Returnvalue,
false, // is nullable
0, // byte precision
0, // byte scale
string.Empty,
DataRowVersion.Default,
null );

command.parameters["@CategoryID"].value = permission.CategoryID;
command.parameters["@RoleName"].value = permission.PermissionName;
command.parameters["@Description"].value = permission.Description;
// 可以返回新的ID值
command.parameters["@RoleID"].Direction = ParameterDirection.Output;

int rowsAffected = command.ExecuteNonQuery();
int result = command.parameters["Returnvalue"].value;
int newID = command.parameters["@RoleID"].value;

  功能挺強的吧,可以得到三個值,分別是行影響值,預存程序傳回值,新的ID值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.