将DAL函数转换为mysql中的存储过程

时间:2010-08-27 16:24:35

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

您好,我的数据访问层的课程包含一个名为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存储过程

1 个答案:

答案 0 :(得分:0)

我不是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电话 GetSqlStringCommand。你需要 将GetSqlStringCommand更改为GetStoredProcCommand。
  2. 您的参数名称必须 改变
  3. 该文本应为sp_search而不是“选择计数(cc.course_id)为'course_count ...”