標籤:io ar os 使用 sp for strong on bs
(1)簡單的無參數預存程序
create procedure ExpOne
as
select top 10 * from Corp
go
C#調用此預存程序
SqlConnection con = new SqlConnection(connstr);
string procedurestr = "預存程序名";
SqlCommand cmd = new SqlCommand(procedurestr, con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
i = cmd.ExecuteNonQuery();//這裡是返回一個最後一次執行所影響的行數.
//如果行數沒有受影響,返回 -1.
con.Close();
(2)通過預存程序使用隱式內聯參數
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER procedure [dbo].[GetCorp]
@id int
as
select * from Corp where [email protected]
C#中調用上面的預存程序
SqlConnection con = new SqlConnection(connstr);
string sqltext = "預存程序名";
SqlCommand cmd = new SqlCommand(sqltext, con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p = new SqlParameter("@id", DbType.Int32);
p.Direction = ParameterDirection.Input;
p.Value = 1739;
cmd.Parameters.Add(p);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
rtn = sdr["UserName"].ToString() + sdr["CorpName"].ToString() + sdr["Intro"].ToString();
}
sdr.Close();
con.Close();
從上面代碼可以看出,但參數個數非常多的時候其實也是非常麻煩的,目前還沒有找到好的解決辦法,大家可以使用參數數組,如果有更好的辦法歡迎一起探討.
SqlParameter[] p ={ new SqlParameter("@id", SqlDbType.Int, 4), new SqlParameter("@UserName", SqlDbType.NVarChar, 50) };
p[0].Value = 1739;
p[0].Direction = ParameterDirection.Input;
p[1].Direction = ParameterDirection.Input;
foreach (SqlParameter pm in p)
{
cmd.Parameters.Add(pm);
}
(3)通過預存程序調用顯式的參數
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER procedure [dbo].[GetMyCorp]
@id int,@UserName nvarchar(50) output
as
select @UserName=UserName from t_jc_corp where [email protected]
在asp.net 中調用該預存程序 得到輸出參數 @UserName
SqlConnection con = new SqlConnection(connstr);
con.Open();
string procedurename = "GetMyCorp";
SqlCommand cmd = new SqlCommand(procedurename, con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter();
p1 = cmd.Parameters.Add("@id",SqlDbType.Int,4);
p1.Direction = ParameterDirection.Input;
p1.Value = 1739;
SqlParameter p2 = new SqlParameter();
p2 = cmd.Parameters.Add("@UserName", SqlDbType.NVarChar, 50);
p2.Direction = ParameterDirection.Output;
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Close();
rtn = p2.Value.ToString();
asp.net 常用的幾種調用預存程序的方法