C# - >我有一个参数化存储过程(SP),它返回一个我想调用的int,并读取我想要分配给隐藏字段的返回值。我相信我已经写了大部分内容但是我坚持最后一部分(实际上是从SP中提取返回的值。帮助将非常感激。这是我到目前为止所拥有的......
public int CheckIP()
{
string conn = "";
conn = ConfigurationManager.ConnectionStrings["Connection"].ToString();
SqlConnection sqlconn = new SqlConnection(conn);
try
{
sqlconn.Open();
DataSet ds = new DataSet();
SqlCommand objcmd = new SqlCommand("sp_CheckIP", sqlconn);
objcmd.CommandType = CommandType.StoredProcedure;
SqlParameter IPAddress = objcmd.Parameters.Add("@IpAddress",
SqlDbType.VarChar);
IPAddress.Value = 0;
SqlDataAdapter objAdp = new SqlDataAdapter(objcmd);
objAdp.Fill(ds);
????
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
finally
{
sqlconn.Close();
}
}
我的存储过程如下:
ALTER Procedure [dbo].[sp_CheckIP]
@IpAddress varchar(15),
@AllowedLogInAttempts int Output
AS
BEGIN
IF (Select Count(IPAddressID) From Emerald.dbo.IPManager
Where IPAddress = @IPAddress) = 1
BEGIN
Select @AllowedLogInAttempts =
CASE
When Trusted = 0 and Block = 0 then '5'
When Trusted = 1 and Block = 0 then '7'
When Trusted = 0 and Block = 1 then '0'
When Trusted = 1 and Block = 1 then '0'
End
FROM Emerald.dbo.IPManager
Where IPAddress = @IPAddress
END
ELSE
Select 3
END
答案 0 :(得分:3)
您需要修改您的代码,如下所示,我已经为SP添加了返回变量并返回输出值。
public int CheckIP()
{
string conn = "";
conn = ConfigurationManager.ConnectionStrings["Connection"].ToString();
SqlConnection sqlconn = new SqlConnection(conn);
try
{
sqlconn.Open();
DataSet ds = new DataSet();
SqlCommand objcmd = new SqlCommand("sp_CheckIP", sqlconn);
objcmd.CommandType = CommandType.StoredProcedure;
SqlParameter IPAddress = objcmd.Parameters.Add("@IpAddress", SqlDbType.VarChar);
IPAddress.Value = 0;
SqlParameter returnParameter = new SqlParameter("@AllowedLogInAttempts", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.Output;
objcmd.Parameters.Add(returnParameter);
objcmd.ExecuteNonQuery();
int id = (int) returnParameter.Value;
//Now here write your logic to assign value hidden field
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
finally
{
sqlconn.Close();
}
}
答案 1 :(得分:0)
你可以使用;
retval = objcmd.ExecuteScalar();
答案 2 :(得分:0)
Select @AllowedLogInAttempts =
CASE
When Trusted = 0 and Block = 0 then '5'
When Trusted = 1 and Block = 0 then '7'
When Trusted = 0 and Block = 1 then '0'
When Trusted = 1 and Block = 1 then '0'
End
FROM Emerald.dbo.IPManager
Where IPAddress = @IPAddress
可缩短为:
Select @AllowedLogInAttempts = (Trusted * 2 + 5) * (Block ^ 1)