【问题标题】:Calling Functions in SqlCommand在 SqlCommand 中调用函数
【发布时间】:2013-02-24 03:41:49
【问题描述】:
public void CreateMySqlCommand() 
 {
    SqlCommand myCommand = new SqlCommand();
    myCommand.CommandText = "SELECT * FROM Categories ORDER BY CategoryID";
    myCommand.CommandTimeout = 15;
    myCommand.CommandType = CommandType.Text;
 }

我可以在 myCommand.CommandText 中使用 Sql Server 函数吗?为什么?

【问题讨论】:

  • 您能解释一下您所说的“SQL Server 函数”是指存储过程吗?
  • “为什么”?!你的意思是“如何”?

标签: c# asp.net sql sql-server tsql


【解决方案1】:

如果你的意思是,SQL Server user defined functions。那么,是的;您可以像这样正常使用它:

myCommand.CommandText = "SELECT fn_Yourfunctionname(@parameternames)";
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.Add(new SqlParameter("@parameternames", ...

之所以起作用,是因为这是在 SQL Server 中直接调用函数的方式。

【讨论】:

    【解决方案2】:

    另一种方法:

        public T ExecuteScalarFunction<T>(string functionName, List<SqlParameter> parameters, SqlDbType returnSqlType) where T : new()
        {
            using (var conn = new SqlConnection(CTX.Database.GetDbConnection().ConnectionString))
            {
                if (conn.State != ConnectionState.Open)
                    conn.Open();
    
                using (var cmd = new SqlCommand(functionName, conn)) { 
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlCommandBuilder.DeriveParameters(cmd);
    
                    foreach (var parameter in parameters)
                    {
                        cmd.Parameters.Add(parameter);
                    }
    
                    cmd.Parameters.Add("@RETURN_VALUE", returnSqlType).Direction = ParameterDirection.ReturnValue;
    
                    cmd.ExecuteNonQuery();
                    return (T)cmd.Parameters["@RETURN_VALUE"].Value;
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2012-12-31
      • 2023-02-22
      • 2014-04-18
      相关资源
      最近更新 更多