在ASP.NET C#中使用SQL Server存储过程输出

4

我刚开始接触存储过程。

我们有一个现有的系统,使用存储过程检查用户名和URL路径。存储过程将检查用户详细信息是否存在。如果存在,则返回1,否则返回0。

我正在尝试编写asp.net代码,通过提供用户详细信息和路径来调用此存储过程,然后在asp.net中使用返回的0或1值。


6
这是一张不错的截图。 - CodeCaster
3
你目前为止有尝试过什么吗? - Chris Gessler
你应该查看 http://www.c-sharpcorner.com/UploadFile/rohatash/get-out-parameter-from-a-stored-procedure-in-Asp-Net/ 。愉快地编码吧! - Ravi Vanapalli
3个回答

8
看起来你需要带有输出参数的存储过程。
int errorId = 0;

using(SqlConnection sqlConnection = new SqlConnection(connectionString))
{
    using(SqlCommand cmd = new SqlCommand("YourStoredProcedureName", sqlConnection))
    {
    cmd.CommandType=CommandType.StoredProcedure;
    SqlParameter parm=new SqlParameter("@username", SqlDbType.VarChar); 
    parm.Value="mshiyam";
    parm.Direction =ParameterDirection.Input ; 
    cmd.Parameters.Add(parm); 

    SqlParameter parm2=new SqlParameter("@path",SqlDbType.VarChar); 
    parm2.value = "Some Path";
    parm2.Direction=ParameterDirection.Output;
    cmd.Parameters.Add(parm2); 


    SqlParameter parm3 = new SqlParameter("@errorId",SqlDbType.Int);
    parm3.Direction=ParameterDirection.Output; 
    cmd.Parameters.Add(parm3); 

    sqlConnection.Open(); 
    sqlConnection.ExecuteNonQuery();

    errorId = cmd.Parameters["@errorId"].Value; //This will 1 or 0
   }

}

1
很棒,你把 SqlConnection 放进了 using().... 块中 - 但是你也应该对 SqlCommand 进行同样的操作! - marc_s
抱歉,@marc_s 打得太快了...我现在会更新帖子。 - HatSoft
难道你的意思不是cmd.ExecuteNonQuery();吗? - Maury Markowitz

1
请使用以下代码:
SqlCommand cmd = new SqlCommand("MyStoredProcedure", cn);
cmd.CommandType=CommandType.StoredProcedure;
SqlParameter parm=new SqlParameter("@username",SqlDbType.VarChar);
parm.Value=strUser;
parm.Direction =ParameterDirection.Input ; 
cmd.Parameters.Add(parm); 
parm=new SqlParameter("@url",SqlDbType.VarChar);
parm.Value=strUrl;
parm.Direction =ParameterDirection.Input ; 
cmd.Parameters.Add(parm); 
parm=new SqlParameter("@errorID",SqlDbType.Int); 
parm.Direction=ParameterDirection.Output; // This is important!
cmd.Parameters.Add(parm); 
cn.Open(); 
cmd.ExecuteNonQuery();
cn.Close(); 

// Print the output value
Console.WriteLine(cmd.Parameters["@errorID"].Value); 
Console.ReadLine();

0
int errorId = 0;

SqlCommand cmd = new SqlCommand("YourSPName", cn);
cmd.CommandType=CommandType.StoredProcedure;
SqlParameter parm=new SqlParameter("@username",SqlDbType.VarChar);
parm.Value=strUser;
parm.Direction =ParameterDirection.Input ; 
cmd.Parameters.Add(parm); 
parm=new SqlParameter("@url",SqlDbType.VarChar);
parm.Value=strUrl;
parm.Direction =ParameterDirection.Input ; 
cmd.Parameters.Add(parm); 
parm=new SqlParameter("@errorID",SqlDbType.Int); 
parm.Direction=ParameterDirection.Output; // This is important!
cmd.Parameters.Add(parm); 
cn.Open(); 
errorId = (int)cmd.ExecuteNonQuery();
cn.Close(); 

sqlConnection.Open(); 
sqlConnection.ExecuteNonQuery();

设置条件:

if(errorId == 1)
{
   `"Allow User here"`
}
if(errorId==0)
{
   `Redirect when you to redirect to use.`
}  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接