如何在ado.net中执行表值函数?

时间:2014-03-27 22:15:28

标签: c# database stored-procedures ado.net stored-functions

我正在使用ado.net。

我的数据库中有一个函数jsp,它接受2个参数并返回一个表。我需要提示用户输入两个参数,然后执行jsp功能并将表打印到屏幕上。这是我现在拥有的:

jspCmd = new SqlCommand(jspStmt, conn);
jspCmd.CommandType = CommandType.StoredProcedure;

jspCmd.Parameters.Add("@snum", SqlDbType.VarChar, 5);
jspCmd.Parameters.Add("@pnum", SqlDbType.VarChar, 5);
jspCmd.Prepare();

Console.WriteLine();
Console.WriteLine(@"Please enter S# and P# separated by blanks, or exit to terminate");
string line = Console.ReadLine();
Regex r = new Regex("[ ]+");
string[] fields = r.Split(line);

if (fields[0] == "exit") break;
jspCmd.Parameters[0].Value = fields[0];
jspCmd.Parameters[1].Value = fields[1];

jspCmd.ExecuteNonQuery();//<---I BELIEVE ERROR COMING FROM HERE

reader = jspCmd.ExecuteReader();//PRINT TABLE TO SCREEN
while (reader.Read())
{
    Console.WriteLine(reader[0].ToString() + "  "
                      + reader[1].ToString()
                      + "  " + reader[2].ToString());
}
reader.Close();

当我运行它时,我输入两个参数并引发异常:

Program aborted: System.Data.SqlClient.SqlException (0x80131904): The request
for procedure 'jsp' failed because 'jsp' is a table valued function object.

有人能告诉我这样做的正确方法吗?

3 个答案:

答案 0 :(得分:7)

确保您的jspStmt是具有常规参数绑定的SELECT,例如:

var jspStmt = "SELECT * FROM myfunction(@snum, @pnum)";
// this is how table-valued functions are invoked normally in SQL.

省略以下内容:

jspCmd.CommandType = CommandType.StoredProcedure; 
// WRONG TYPE, leave it as CommandType.Text;

省略以下内容:

jspCmd.ExecuteNonQuery();//<---I BELIEVE ERROR COMING FROM HERE
// WRONG KIND OF RESULT, it **IS** a query.  Further, let your
// later jspCmd.ExecuteReader() invoke it and get the actual data.

答案 1 :(得分:4)

要执行表值函数,请使用SELECT作为文本命令:

jspCmd = new SqlCommand("SELECT * FROM " + jspStmt + "()", conn);
jspCmd.CommandType = CommandType.Text;

要获得结果,请使用ExecuteReader - 您已经在之后使用ExecuteNonQuery,这是INSERT s,{{1}等等。

答案 2 :(得分:0)

要添加到D Stanley的答案,看起来你得到的新异常是由于错误地调用了该函数。请尝试以下操作(更正了select语句并向函数添加了参数):

jspCmd = new SqlCommand("SELECT * FROM jsp('" + fields[0] + "', '" + fields[1] + "')", conn);

然后像你一样继续使用ExecuteReader