我正在使用 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.
任何人都可以告诉我正确的方法吗?
最佳答案
确保您的 jspStmt 是具有常规参数绑定(bind)的 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.
关于c# - 如何在 ado.net 中执行表值函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22700374/