繁体   English   中英

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

[英]How to execute a table-valued function in ado.net?

我正在使用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是一个带有常规参数绑定的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.

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

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

要获得结果,请使用ExecuteReader - 您已经使用了ExecuteReader但是使用ExecuteNonQuery ,这是用于INSERTUPDATE等。

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

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

然后像你一样继续使用ExecuteReader

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM