为什么执行时没有返回结果?

时间:2016-07-24 00:12:15

标签: c# asp.net .net sql-server stored-procedures

SqlConnection conn = getConnection();
SqlCommand cmd = new SqlCommand();

cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SP_PSLA_SEARCH"; //The stored procedure gets added
cmd.CommandTimeout = 0;
cmd.Connection = conn;

// Start adding the parameters of the stored procedure
cmd.Parameters.AddWithValue("@usrnm", thisUser.Username);

int constit = 0;

if (thisUser.Constituencies.Count > 0)
{
    foreach (KeyValuePair<int, string> kp in thisUser.Constituencies)
    {
        if (kp.Value == ddlConstituency.SelectedValue.ToString())
        {
            constit = kp.Key;
            break;
        }
    }
}

cmd.Parameters.AddWithValue("@cnstncy", constit);

string pdval = null;
int valtype = 0;

if (rbsearchradios.SelectedIndex == 0)
{
    try
    {
        pdval = searchVal;
        cmd.Parameters.AddWithValue("@Search", DBNull.Value);
        cmd.Parameters.AddWithValue("@pd", int.Parse(pdval));
        cmd.Parameters.AddWithValue("@type", valtype);
    }
    catch
    {
        System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "stop", "alert('Invalid PD Number Supplied! Please Provide A Valid Submission.');", true);
        return;
    }
}
else
{
    valtype = 1;
    cmd.Parameters.AddWithValue("@Search", searchVal);
    cmd.Parameters.AddWithValue("@pd", DBNull.Value);
    cmd.Parameters.AddWithValue("@type", valtype);
}

cmd.Parameters.AddWithValue("@app", 1);

conn.Open();                        

// Creates Dataadapter for execution
SqlDataAdapter dp2 = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();

dp2.Fill(ds, "name");

我正在尝试存储过程的参数并且执行此存储过程并将此结果导入数据集但我什么都没得到。字面意思。没有例外,只是存储过程没有结果。

这是存储过程:

DECLARE @return_value int

EXEC    @return_value = [dbo].[SP_PSLA_SEARCH] 
            @usrnm = N'tstone',
            @cnstncy = 55,
            @Search = N'primary',
            @pd = NULL,
            @type = 1,
            @app = 1

SELECT  'Return Value' = @return_value
GO

1 个答案:

答案 0 :(得分:0)

进行问题排查:

  1. 确保每个参数具有哪些值,并在Sql Server Management Studio中直接对数据库执行相同的查询。
  2. 检查您是否正确使用了数据集中的结果(代码中不清楚)
  3. 通常,您还可以尝试简化并使代码更加清晰:

    • 返回的块和if (rbsearchradios.SelectedIndex == 0)可以在开头移动,创建SqlCommand然后中断
    • 是没有意义的
    • 如果SP仅返回单个值,则可以使用ExecuteScalar()方法,这种方法更快更直接。