SQL Server How to call a scalar valued function from C# and get its value?

dsekswqp  于 2023-04-10  发布在  Scala
关注(0)|答案(1)|浏览(151)

How can I run a scalar valued function from c# and get its value? For a table-based function, I use a select command and get the resulting DataTable, but I am clueless on how to do it with scalar valued functions.

dwthyt8l

dwthyt8l1#

You can pass a string to SQL and have it do anything that SQL can do using SqlConneciton and 'SqlCommand'.

string sqlcheck = "SELECT * FROM " + table + " WHERE CUST_NO = @customerNumber";

using (SqlConnection connect = new SqlConnection(DBConnection String))
{
   using (SqlCommand command = new SqlCommand(sqlcheck, connect))
   {
     command.Parameters.AddWithValue("@customerNumber", customerNumber);
     connect.Open();
     response = (string)(command.ExecuteScalar());
   }
}

You can use ExecuteScalar or one of the other execution methods. http://msdn.microsoft.com/en-us/library/182ax5k8.aspx

You can make your SQL string do any SQL, and return/not return using the different execution methods.

相关问题