我在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 …Run Code Online (Sandbox Code Playgroud) 我正在使用MySQL连接器.
using (MySqlConnection connection = new MySqlConnection("..."))
{
connection.Open();
MySqlCommand command = new MySqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "FN_NEW";
command.Parameters.AddWithValue("P_SESSION_ID", sessionId);
command.Parameters.AddWithValue("P_NAME", deckName);
object result = command.ExecuteScalar(); // returns NULL !!!!!!!!!
return Json(result);
}
Run Code Online (Sandbox Code Playgroud)
由于某种原因,返回的valus为null.我使用正确的CommandType吗?
我如何从.NET调用MySQL函数?
最终的工作版本是:
using (MySqlConnection connection = new MySqlConnection(GetConnectionString().ConnectionString))
{
connection.Open();
MySqlCommand command = new MySqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "FN_NEW";
command.Parameters.AddWithValue("P_SESSION_ID", sessionId);
command.Parameters.AddWithValue("P_NAME", deckName);
MySqlParameter returnParam = command.Parameters.Add("@RETURN_VALUE", MySqlDbType.Int32);
returnParam.Direction = System.Data.ParameterDirection.ReturnValue;
command.ExecuteNonQuery();
NewDeckReturnCode result = (NewDeckReturnCode)returnParam.Value; …Run Code Online (Sandbox Code Playgroud) 我想在SQL Server中创建调用函数,它接收两个参数并返回一个整数.当我调用存储过程时,我使用以下代码:
sqlcmd.CommandType = CommandType.StoredProcedure
sqlcmd.CommandText = "PROCEDURE_NAME"
sqlcmd.Parameters.Add(New SqlClient.SqlParameter("@param1", Utilities.NothingToDBNull(user)))
sqlcmd.Parameters.Add(New SqlClient.SqlParameter("@param2", Utilities.NothingToDBNull(password)))
da = New SqlClient.SqlDataAdapter()
da.SelectCommand = sqlcmd
table = New DataTable()
da.Fill(table)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我有一个由存储过程返回的表.如果我想使用一个返回标量值而不是存储过程的函数会发生什么变化?