带字符串的SQL查询不像条件

时间:2013-01-04 10:08:00

标签: c# sql-server

我有一个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'

如何做到这一点

3 个答案:

答案 0 :(得分:1)

它必须是带引号的字符串,您应该使用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对象用参数填充查询。

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

找出发送给SQL Server的查询。

  1. 来自代码(您的查询字符串)。
  2. 使用SQL Server Profiler(从Microsoft SQL Server Management Studio&gt;工具&gt; SQL Server Profiler打开)。
  3. 代码中的查询与管理工作室中的查询必须有所不同。