DbCommand,必须声明变量错误

时间:2014-03-06 07:55:20

标签: ado.net dbcommand

这是我的代码。我也添加了db参数,但它仍然显示错误(执行时)。必须声明一个标量变量

       DbCommand command;
        StringBuilder query = new StringBuilder(
                                                        @"SELECT         isnull(UpsellService_OID,'') UpsellService_OID," + Environment.NewLine +
                                                        "       isnull(ServiceName,'') ServiceName," + Environment.NewLine +
                                                        "       isnull(ServiceDescription,'') ServiceDescription," + Environment.NewLine +
                                                        "       isnull(Create_By,'') Create_By," + Environment.NewLine +
                                                        "       isnull(Create_Date,'') Create_Date," + Environment.NewLine +
                                                        "       isnull(Modify_By,'') Modify_By," + Environment.NewLine +
                                                        "       isnull(Modify_Date,'') Modify_Date," + Environment.NewLine +
                                                        "       isnull(Active_f,'') Active_f" + Environment.NewLine +
                                                        "FROM   TRGPAYROLL.ZONG.UPSELLSERVICES   " + Environment.NewLine +
                                                        "WHERE  1 = 1");
        if (!string.IsNullOrEmpty(idObject.ServiceName))
        {
            query.Append(" AND ServiceName like '%'  @ServiceName  '%'");
        }

        command = db.GetSqlStringCommand(query.ToString());
        if (!string.IsNullOrEmpty(idObject.ServiceName))
        {
            db.AddInParameter(command, "ServiceName", DbType.String, idObject.ServiceName);
        }

        return command;

2 个答案:

答案 0 :(得分:1)

我会以这种方式重写代码的最后一部分

    if (!string.IsNullOrEmpty(idObject.ServiceName))
    {
        query.Append(" AND ServiceName like @ServiceName");
    }

    command = db.GetSqlStringCommand(query.ToString());
    if (!string.IsNullOrEmpty(idObject.ServiceName))
    {
        db.AddInParameter(command, "@ServiceName", DbType.String, "%" + idObject.ServiceName + "%");
    }

通配符直接添加到参数的值,而参数的占位符应该没有任何字符串连接。然而,有许多细节缺失,以确保这个答案的正确性。特别是我只能假设方法GetSqlStringCommandAddInParameter

的内部工作原理

答案 1 :(得分:0)

@ServiceName变量未在SQL语句中声明。在它的开头附加类似

的内容
DECLARE @ServiceName AS nchar(32)
SET @ServiceName = ....