2016-10-19 223 views
1

我有這樣的代碼...在C#與參數SQL查詢字符串參數C#

var sql = @"select * from Passenger t0  
      join Ticket t1 on t0.PassengerID = t1.PassengerID    
      where t1.IsArrived = @IsArrived "; 
      List<SqlParameter> parameters = new List<SqlParameter>() { 
        new SqlParameter 
        { 
         ParameterName = "DateFrom", 
         Value = (object)fromDate ?? DBNull.Value, 
         DbType = System.Data.DbType.DateTime 
        }, 
        new SqlParameter 
        { 
         ParameterName = "DateTo", 
         Value = (object)toDate ?? DBNull.Value, 
         DbType = System.Data.DbType.DateTime 
        }, 
        new SqlParameter 
        { 
         ParameterName = "IsArrived", 
         Value = route, 
         DbType =System.Data.DbType.Boolean 
        }, 
         new SqlParameter 
        { 
         ParameterName = "Search", 
         Value = $"'%{searchString}%'", 
         DbType = System.Data.DbType.String 
        } 
       }; 
      var sqlQuery = sql + 
       (fromDate != null ? "and t1.DateFrom >= @DateFrom " : " ") + 
       (toDate != null ? "and @DateTo >= t1.DateFrom" : " ") + 
       (!String.IsNullOrEmpty(searchString) ? "and (t0.FirstName like @Search or t0.LastName like @Search)" : " "); 

參數「@Search」壞查詢 - 我怎麼能修改此查詢工作? 我不知道如何編寫此參數的值。 我試圖

Value = [email protected]"'%{searchString}%'" 
Value = @"'%"+searchString+"%'", 
Value = $"\u0027\u0025{searchString}\u0025\u0027", 
Value = "\u0027\u0025"+searchString+"\u0025\u0027", 
Value = "\'%"+searchString+"%\'" 
+0

請不要添加這樣的參數不可讀。 – mybirthname

+4

使用'Value = $「%{searchString}%」'? – Phylogenesis

+0

Value = $「%{searchString}%」 - 它的工作! <3 –

回答

0

var sqlQuery = sql + (fromDate != null ? "and t1.DateFrom >= @DateFrom " : " ") + (toDate != null ? "and @DateTo >= t1.DateFrom" : " ") + (!String.IsNullOrEmpty(searchString) ? "and (t0.FirstName like @Search or t0.LastName like ' + @Search+ ')" : " ");

不要讓@Search內的字符串。