Ree*_*iie 6 c# database ado.net stored-procedures 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();
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我输入两个参数并引发异常:
Program aborted: System.Data.SqlClient.SqlException (0x80131904): The request
for procedure 'jsp' failed because 'jsp' is a table valued function object.
Run Code Online (Sandbox Code Playgroud)
有谁能告诉我这样做的正确方法?
确保你的jspStmt是一个带有常规参数绑定的SELECT,例如:
var jspStmt = "SELECT * FROM myfunction(@snum, @pnum)";
// this is how table-valued functions are invoked normally in SQL.
Run Code Online (Sandbox Code Playgroud)
省略以下内容:
jspCmd.CommandType = CommandType.StoredProcedure;
// WRONG TYPE, leave it as CommandType.Text;
Run Code Online (Sandbox Code Playgroud)
省略以下内容:
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.
Run Code Online (Sandbox Code Playgroud)
要执行表值函数,请使用SELECT文本命令:
jspCmd = new SqlCommand("SELECT * FROM " + jspStmt + "()", conn);
jspCmd.CommandType = CommandType.Text;
Run Code Online (Sandbox Code Playgroud)
要获得结果,请使用ExecuteReader- ,您已经这样做了,但在使用之后ExecuteNonQuery,它用于INSERTs、UPDATEs 等。
| 归档时间: |
|
| 查看次数: |
10880 次 |
| 最近记录: |