2014-03-06 142 views
0

這是我的代碼。我也添加了db參數,但它仍然顯示我錯誤(執行時)。必須聲明一個標量變量DbCommand,必須聲明變量錯誤

 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; 

回答

0

@ServiceName變量未在您的SQL語句中聲明。追加到它beggining像

DECLARE @ServiceName AS nchar(32) 
SET @ServiceName = .... 
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的內部工作原理