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

Reeggiie picture Reeggiie · Mar 27, 2014 · Viewed 12.8k times · Source

I am using ado.net.

I have a function jsp in my database that takes 2 parameters and returns a table. I need to prompt the user for the two parameters, then execute the jsp function and print the table to the screen. Here is what I currently have:

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();

When I run this, I enter the two params and an exception is raised:

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

Can anyone show me the correct way to do this?

Answer

David Bullock picture David Bullock · Feb 17, 2015

Make sure your jspStmt is a SELECT with regular parameter binding, eg:

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

Omit the following:

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

Omit the following:

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.