Sql查询字符串不像条件

本文关键字:条件 字符串 查询 Sql | 更新日期: 2023-09-27 17:50:44

我有一个sql查询

Select Itemcode from StocktransferlocationDetails 
where Projectname='" +  projectname_stockout + "'  and 
       Stocktransferlocation !='" + location_stockout + "' and Status='Open'

在c#中使用时不正确工作,但在SQl中正确工作,我在SQl

中使用了以下查询
  Select Itemcode from StocktransferlocationDetails 
  where Projectname='iupl'  and Stocktransferlocation !='Chennai-Bangalore' 
        and Status='Open'

怎么做

Sql查询字符串不像条件

它必须是一个带引号的字符串,你应该使用SqlParameter来防止Sql注入。

var sql = "Select Itemcode 
              from StocktransferlocationDetails 
              where Projectname = @ProjectName  
              and Stocktransferlocation <> @Stocktransferlocation 
              and Status='Open'";
var param1 = new SqlParameter("@ProjectName", projectname_stockout);
var param2 = new SqlParameter("@Stocktransferlocation", location_stockout);

这只是解决方案的一部分,您应该使用SqlCommand对象用参数填充查询。

在c#中你应该这样使用:-

string query="Select Itemcode from StocktransferlocationDetails"+ 
+" where Projectname=" +  projectname_stockout + "  and "+
      +" Stocktransferlocation !=" + location_stockout + " and Status='open'";

找出发送到SQL Server的查询。

    从代码(您的querystring)。
  1. 使用SQL Server Profiler(从Microsoft SQL Server Management Studio> tools> SQL Server Profiler中打开)。

代码中的查询和管理工作室中的查询一定有不同之处。