資料庫端:建立預存程序
CREATE PROC P_TEST
@Name VARCHAR(20),
@Rowcount INT OUTPUT
AS
BEGIN
SELECT * FROM T_Customer WHERE NAME = @Name
SET @Rowcount = @@ROWCOUNT
END
GO
-- 測試呼叫
DECLARE @i INT
EXEC P_TEST 'A', @i OUTPUT
SELECT @i
Web.config 連線字串設定
<configuration>
<appSettings>
<add key="ConnectString" value="server=(local);User ID=sa;Password=;database=Test" />
</appSettings>
</configuration>
C# 後端代碼 (Web Forms)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class StoredProcDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ExecuteStoredProcedure();
}
}
private void ExecuteStoredProcedure()
{
string connStr = ConfigurationManager.AppSettings["ConnectString"];
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("P_TEST", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// 輸入參數
cmd.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = "A";
// 輸出參數
SqlParameter outParam = cmd.Parameters.Add("@Rowcount", SqlDbType.Int);
outParam.Direction = ParameterDirection.Output;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds, "CustomerTable");
// 取得輸出參數值
int rowCount = Convert.ToInt32(outParam.Value);
lblRowCount.Text = $"影響列數: {rowCount}";
}
}
// 繫結結果到 GridView
gvResult.DataSource = ds.Tables["CustomerTable"];
gvResult.DataBind();
}
}
關鍵點總結
CommandType.StoredProcedure 告知 ADO.NET 執行的是預存程序而非 T-SQL 批次。
- 輸出參數必須設定
Direction = ParameterDirection.Output (或 InputOutput)。
SqlDataAdapter.Fill 會自動開啟/關閉連線,但輸出參數值需在 Fill 完成後從 cmd.Parameters["@Rowcount"].Value 讀取。
- 使用
using 區塊確保連線與命令物件正確釋放。
進階建議
- 採用
ExecuteNonQuery 僅取輸出參數時,不需 SqlDataAdapter。
- 實務上建議將資料存取邏輯封裝於 Repository/DAL 層,頁面僅呼叫服務方法。
- 參數化查詢已防止 SQL Injection,切勿使用字串拼接組裝 SQL。