2014-03-27 16 views
3

我正在使用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. 

谁能告诉我正确的方式做到这一点?

回答

4

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

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

而得到的结果使用ExecuteReader - 你已经这样做了,但后您使用ExecuteNonQuery,这是INSERT小号,UPDATE s等

+0

我尝试这样做,我正在得到一个新的例外。我的jspStmt =“jsp”,因为那是函数的名字。异常是:程序中止:System.Data.SqlClient.SqlException(0x80131904):无效列 名称'jsp'。 声明无法准备。 – Reeggiie

+0

@ user3345200忘了添加圆括号 - 现在就试试吧。 –

+0

我添加了(),它现在改为:程序异常终止:System.Data.SqlClient.SqlException(0x80131904):'jsp'不是 公认的内置函数名称。 声明无法准备。 ---- jsp位于我的数据库的过程文件夹中。任何想法为什么它会给我这个? – Reeggiie

0

要添加到D斯坦利的答案,它看起来像你得到的新例外是由于错误地调用该函数。请尝试以下(纠正的SELECT语句,并添加参数的功能):

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

然后继续使用ExecuteReader像你这样。

+0

这是不安全的。通过不正确地参数化SQL语句,可能会导致SQL注入攻击。请参阅大卫布洛克的答案为一个适当的例子。 – David

6

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

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.