DbCommand , Must Declare a variable error

290 Views Asked by At

This is my code. I have added the db parameter too but it still shows me error (on execution). Must declare a scalar variable

       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

There are 2 best solutions below

0
ttaaoossuuuu On

@ServiceName variable is not declared in your SQL statement. Append to beggining of it something like

DECLARE @ServiceName AS nchar(32)
SET @ServiceName = ....
0
Steve On

I would rewrite the last part of your code in this way

    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 + "%");
    }

The wildcard are added directly to the value of the parameter, while the placeholder of the parameter should be free from any string concatenations. However there are many details missing to be sure of the correctness of this answer. In particular Ican only assume the inner workings of the methods GetSqlStringCommand and AddInParameter