如何在C#中调用SQL函数?

Rik*_*ika 7 c# sql function sql-server-2008

我在SQL中创建了一个函数,现在我需要在我的C#应用​​程序中使用该函数.

我尝试使用这样的东西,但似乎我做错了,因为我得到了:

Must declare the scalar value '@2064734117'
Run Code Online (Sandbox Code Playgroud)

...当我2064734117作为第一个参数和1第二个参数给出时.这是我正在谈论的代码:

SqlConnection con = new SqlConnection(clsDb.connectionString);
string query = string.Format("select Function1(@{0},@{1}) ",
  int.Parse(e.CurrentRow.Cells["CodeMeli"].Value.ToString()),1);
con.Open();
SqlCommand cmd = new SqlCommand(query,con);
SqlDataAdapter READER = new SqlDataAdapter();
READER.SelectCommand = cmd;
DataTable table = new DataTable();
READER.Fill(table);
radGridView1.DataSource = table;
con.Close();
Run Code Online (Sandbox Code Playgroud)

我的函数接受两个整数参数并返回一个表.我在Visual Studio中检查了它并且它有效,但我无法在我的应用程序中使用它.

这是我的功能声明:

ALTER FUNCTION dbo.Function1
(
/*
@parameter1 int = 5,
@parameter2 datatype
*/
@ID int,
@clsTypeID int
)
    RETURNS TABLE/* @table_variable TABLE (column1 datatype, column2 datatype) */
    AS
         /*BEGIN */
    /* INSERT INTO @table_variable
       SELECT ... FROM ... */
RETURN SELECT  * FROM tblCLASS2 
        WHERE STNID = @ID AND CLASSTYPEID =  @clsTypeID  
/*END */
/*GO*/
Run Code Online (Sandbox Code Playgroud)

Mit*_*dir 11

你的SQL有点偏,它应该是:

  string query = string.Format("select * from dbo.Function1({0},{1});", int.Parse(e.CurrentRow.Cells["CodeMeli"].Value.ToString()),1);
Run Code Online (Sandbox Code Playgroud)

您可能希望使用SqlParameter对象来阻止sql注入:

  string query = "select * from dbo.Function1(@pa1,@par2);";
  cmd.Parameters.Add("@par1", SqlDbType.Int).Value = int.Parse(e.CurrentRow.Cells["CodeMeli"].Value.ToString());  
  cmd.Parameters.Add("@par2", SqlDbType.Int).Value = 1;
Run Code Online (Sandbox Code Playgroud)