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*/
We can execute a function in C# using a SqlCommand object and passing a SQL defined function in a SELECT SQL query.
Yes you can call a function inside a function.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With