【问题标题】:Convert DAL function into Stored Procedures in mysql将 DAL 函数转换为 mysql 中的存储过程
【发布时间】:2011-04-04 21:56:21
【问题描述】:

您好,我的数据访问层有一个类,其中包含一个名为 GetCitiesByLocation 的函数,它看起来像这样

public DataTable GetCitiesByLocation(long pStateID, string pKeyword)
{

    //create database object
    Database db = DBHelper.CreateDatabase();

    //create SELECT sql statement to be executed using string builder
    //add WHERE 1 = 1 at the end

    //add where [optional] statements
    if (String.IsNullOrEmpty(pKeyword) == false)
    {
        //Create AND statement for ?Keyword
    }

    //add group by order by queries
    sql.Append(" GROUP BY c.city_id ");
    sql.Append(" ORDER BY city_name ");

    //Convert SQL String To DbCommand Object
    DbCommand comm = db.GetSqlStringCommand(sql.ToString());

    //Map Variables to mysql ?Parameters
    db.AddInParameter(comm, "?StateID", DbType.Int64, pStateID);
    db.AddInParameter(comm, "?Keyword", DbType.String, pKeyword);

    try
    {
        //execute sql statement and return results
    }

    catch (Exception ex)
    {
        throw ex;
    }
}

在这里查看完整版:http://friendpaste.com/6ZGJHRNxQ9J57ntFD5XZi1

我想将其转换为 MYSQL 存储过程

这是我朋友将其转换为 MSSQL 存储过程的失败尝试

ALTER PROCEDURE [dbo].[sp_Search]
@Keyword varchar(30)

AS

SELECT count(cc.course_id) as 'course_count',  c.*, con.* FROM city c
LEFT JOIN countries con on con.country_id = c.country_id
LEFT JOIN courses cc on cc.city_id = c.city_id
WHERE 1 = 1
AND CASE @Keyword WHEN (@Keyword <> NULL) THEN (AND c.state_name like @Keyword)  END
AND CASE @Keyword WHEN (pStateID > 0) THEN (AND c.state_id = @StateID AND c.country_id = 69 AND c.province_id = 0) END
AND CASE @Keyword WHEN (pProvinceID  > 0) THEN (AND c.province_id = @ProvinceID AND c.country_id = 52 AND c.state_id = 0) END

我还有事务性 DAL,我想将其转换为 mysql 存储过程

【问题讨论】:

    标签: c# mysql stored-procedures data-access-layer


    【解决方案1】:

    我不是 MySQL 方面的专家,但您似乎正在尝试以与执行参数化查询相同的方式执行存储过程,但这是行不通的。

    如果您的 MSSQL Proc 按照我的预期编译,我也会感到非常惊讶,您的 proc 会以

    开头
      ALTER PROCEDURE [dbo].[sp_Search]
        @Keyword varchar(30),
        @StateID int = null,
        @ProvinceID int = null
    

    或者在 MySQL 中

    CREATE PROCEDURE sp_Search(Keyword varhar(30),
    StateID int,
    ProviceId int)
    

    您最希望通过以下方式更改您的 DAL

    1. 您现有的 DAL 调用 获取SqlStringCommand。你需要 将其更改为 GetSqlStringCommand 为 GetStoredProcCommand。
    2. 您的参数名称必须 改变
    3. 文本应该是 sp_search 而不是“Select count(cc.course_id) as 'course_count...”

    【讨论】:

    • 嗨,我知道如何访问存储过程,存储过程示例中的参数被故意截断,只是为了表示我想要的示例输出。我想将具有一系列 if 语句的 DAL 后面的现有代码转换为存储过程。
    猜你喜欢
    • 2021-12-12
    • 2015-08-28
    • 2010-10-23
    • 2021-08-17
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    相关资源
    最近更新 更多