Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a SQL function in C#?

I have created a function in SQL, now I need to use that function in my C# application.

I tried using something like this, but it seems I'm doing it wrong since I'm getting:

Must declare the scalar value '@2064734117'

...when I give 2064734117 as the first parameter and 1 as the second parameter. Here is the code I'm talking about:

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

And my function takes two integer parameters and returns a table. I checked it in Visual Studio and it worked, but I couldn't get it to work in my application.

And this is my function declaration:

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*/
like image 567
Hossein Avatar asked Aug 03 '12 13:08

Hossein


People also ask

Can I call SQL function from C#?

We can execute a function in C# using a SqlCommand object and passing a SQL defined function in a SELECT SQL query.

Can we call function from function in SQL?

Yes you can call a function inside a function.

How do you call a function in a procedure?

The syntax for a call to a Function procedure is as follows. When you call a Function procedure, you do not have to use its return value. If you do not, all the actions of the function are performed, but the return value is ignored. MsgBox is often called in this manner.


1 Answers

Your SQL is a bit off, it should be:

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

You might want to use SqlParameter-objects to prevent sql injections:

  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;
like image 99
Mithrandir Avatar answered Sep 29 '22 06:09

Mithrandir