使用OR语句查询数据库的最佳方法

时间:2009-05-22 16:17:26

标签: subsonic

我正在尝试将以下sql脚本创建为可以与集合一起使用的亚音速查询:

Select * from tableA
where tableA.InvoiceID = @Invoice
and tableA.VersionID = @VersionID
and tableA.ActiveDate >= GetDate()
and (tableB.InActiveDate is null or tableB.InActiveDate <= GetDate())

这是我目前的代码:

orders = new OrdersCollection();
query = new SubSonic.Query(Tables.Orders);
query.WHERE("InvoiceID", Invoice.InvoiceID);
query.AND("VersionID", version.VersionID);
query.AND("ActiveDate", SubSonic.Is.LessThanOrEqualTo(System.DateTime.Now.ToString()).Value);
query.AND("InActiveDate", SubSonic.Comparision.Is, null).OR("InActiveDate", SubSonic.Is.GreaterThanOrEqualTo("System.DateTime.Now.ToString()).Value);

query.CommandTimeOut = intSubSonicTimeOut; partXrefColl.Load(FilePartXref.FetchByQuery(查询));

我认为我遇到的问题是日期和OR语句的评估。我只使用InvoiceID和VersionID尝试了它,然后我将数据返回到集合中。

非常感谢任何帮助。

6 个答案:

答案 0 :(得分:0)

您的SQL显示“小于或等于”运算符(&lt; =),但您的代码是GreaterThanOrEqualTo()。逻辑的逆转会导致你的问题吗?

答案 1 :(得分:0)

很抱歉,sql查询的正确语法应该是:

Select * from tableA
where tableA.InvoiceID = @Invoice
and tableA.VersionID = @VersionID
and tableA.ActiveDate <= GetDate()
and (tableB.InActiveDate is null or tableB.InActiveDate >= GetDate())

守则应该是:

orders = new OrdersCollection();
query = new SubSonic.Query(Tables.Orders);
query.WHERE("InvoiceID", Invoice.InvoiceID);
query.AND("VersionID", version.VersionID);
query.AND("ActiveDate", SubSonic.Is.LessThanOrEqualTo(System.DateTime.Now.ToString()).Value);
query.AND("InActiveDate", SubSonic.Comparision.Is, null).OR("InActiveDate", SubSonic.Is.GreaterThanOrEqualTo("System.DateTime.Now.ToString()).Value);

orders.Load(Invoices.FetchByQuery(查询);

很抱歉这个混乱。

答案 2 :(得分:0)

疯狂猜测:

“SubSonic.Comparision.Is,null”未映射到“IS NULL”,而是映射到“= NULL”

答案 3 :(得分:0)

假设您使用的是SubSonic 2.1或更高版本,您可以将该查询编写为:

OrdersCollection orders = DB.Select.From(Orders.Schema)
  .Where(Orders.Columns.InvoiceID).IsEqualTo(1)
  .And(Orders.Columns.VersionID).IsEqualTo(1)
  .And(Orders.Columns.ActiveDate).IsLessThanOrEqualTo(DateTime.Now)
  .AndExpression(Orders.Columns.InActiveDate).IsNull()
  .Or(Orders.Columns.InActiveDate).IsGreaterThanOrEqualTo(DateTime.Now)
  .ExecuteAsCollection<OrdersCollection>();

AndExpression将导致嵌套后的Or约束

答案 4 :(得分:0)

亚当确切地说 - 你缺少的是它的表达部分,它是用AndExpression给出的

答案 5 :(得分:0)

经过一些调试后,我能够用以下内容完成查询:

 OrderColl =  DB.Select().From(Orders.Schema)
                    .Where(Orders.Columns.VersionID).IsEqualTo(version.VersionID)
                    .And(Orders.Columns.FulfillNumber).IsEqualTo(invoice.InvocieID)
                    .And(Orders.Columns.ActiveDate).IsLessThanOrEqualTo(DateTime.Now)
                    .AndExpression(Orders.Columns.InactiveDate).IsNull()
                    .Or("InActiveDate").IsGreaterThanOrEqualTo(DateTime.Now)
                    .ExecuteAsCollection<OrdersCollection>();  

感谢所有人的帮助。