我尝试获取其他表中使用的记录数,但是SQL返回null

这是我的代码:

    DBConnectionClass.Command.CommandText = "SELECT COUNT(IMO) FROM vessel
    WHERE ('" + IMO + "' = (SELECT IMO FROM ActOfExemption)) OR ('" + IMO + "' = (SELECT IMO FROM Waybill))";
    object SQL = DBConnectionClass.Command.ExecuteScalar();
    byte Result = Convert.ToByte(SQL);


相同查询但有效且没有子查询:

   DBConnectionClass.Command.CommandText = "SELECT COUNT(IMO) FROM ActOfExemption WHERE IMO = '" + IMO + "'";
   object SQL = DBConnectionClass.Command.ExecuteScalar();
   byte Result = Convert.ToByte(SQL);

   DBConnectionClass.Command.CommandText = "SELECT COUNT(IMO) FROM Waybill WHERE IMO = '" + IMO + "'";
   SQL = DBConnectionClass.Command.ExecuteScalar();
   Result += Convert.ToByte(SQL);


如何在一个带有子查询的查询中做到这一点?

最佳答案

正如@maccettura所建议的那样,考虑更改代码,因为它易于SQL注入。
看来,您正在尝试从ActOfExemption或WAybill中存在IMO的船只中获取IMO。如果是这样,您可以从

DBConnectionClass.Command.CommandText = "SELECT COUNT(IMO) FROM vessel WHERE ('" + IMO + "' = (SELECT IMO FROM ActOfExemption)) OR ('" + IMO + "' = (SELECT IMO FROM Waybill))";



DBConnectionClass.Command.CommandText = "SELECT COUNT(IMO) FROM vessel WHERE ('" + IMO + "' IN (SELECT IMO FROM ActOfExemption)) OR ('" + IMO + "' IN (SELECT IMO FROM Waybill))";

同样,这也不是有效的方法。实际上,您可以使用ActOfExemption左连接容器表,并使用Waybill左连接,并考虑这两个表上IMO为NOT NULL的行。

10-06 08:39