【问题标题】:Query string not being executed properly查询字符串未正确执行
【发布时间】:2021-10-13 09:45:03
【问题描述】:

我正在使用SqlCommand 执行查询:

string query = "select distinct c.Id, a.FirstName, a.LastName 
    from dbo.Customer c, dbo.Customer_CustomerRole_Mapping ccrm, dbo.Address a 
    where ccrm.CustomerRole_Id = 14 AND ccrm.Customer_Id = c.Id and a.Email = c.Email;";
string dbConnection = "Data Source=..."; // this is working, I tested it
SqlConnection connection = new SqlConnection(dbConnection);    
SqlCommand com = new SqlCommand(query, connection);
connection.Open();
SqlDataReader reader = com.ExecuteReader();

// ...Parse reader...

字符串查询在 DBMS 中进行了测试,我应该得到 6 个结果,但是当我将它与 SqlCommand 一起使用时,我得到 0 个结果,连接工作正常,我对其进行了测试,我还使用更简单的查询对其进行了测试(例如select Id from dbo.Customer),它们也很好用。谁能发现我做错了什么?问题一定是查询字符串,也许是别名?

PS.:当然,我将使用参数,但对于这个示例,它只会增加混乱。我也在考虑使用 LINQ,但现在我只需要它按原样工作。

【问题讨论】:

  • 您采取了哪些步骤来解决您的查询问题?
  • 您能否通过添加以下语句进行测试 - com.CommandType = CommandType.Text;
  • @DanielMann,这就是我所描述的,我测试了连接,它工作正常,我尝试了一个更简单的查询,它也工作,所以问题必须在查询本身,也许是别名.
  • 这是在不同的实例或数据库中执行的,其中一个是 6 行,另一个是 0?
  • @Sibgath 会做

标签: c# sql sql-server .net-core


【解决方案1】:

你可以试试这个查询

var  query = "select distinct c.Id, a.FirstName, a.LastName from Customer c 
left  join Customer_CustomerRole_Mapping ccrm  on  c.Id = ccrm.Customer_Id 
 left  join Address a on c.Email = a.Email
 where ccrm.CustomerRole_Id = 14;"

【讨论】:

  • 不一定——即使不推荐,像ccrm.Customer_Id = c.Id and a.Email = c.Email 这样的连接也是有效的
  • 我只是提议尝试
  • 它工作,干得好。为什么原版不行?
  • 原来是一个内连接查询,所以我猜一个表不包含另一个表中使用的键
  • @anastaciu 您使用了内部联接。当某些列具有空值时,将省略整个记录。在这种情况下,您必须使用外连接 - 左或右。
猜你喜欢
  • 1970-01-01
  • 2019-05-10
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-09
相关资源
最近更新 更多