【问题标题】:How to query with this Select statement in vb.net如何在 vb.net 中使用此 Select 语句进行查询
【发布时间】:2018-06-17 04:33:46
【问题描述】:

我在 SQL Server 2008 中使用这条 SQL 语句进行查询:

select 
    sum(tax + debit) + (select isnull(sum(tax + credit), 0)
                        from BILLTRANSACTION 
                        where (BillClass = 2 or BillClass = 5 or BillClass = 6)      
                          and (ClientID = 101383)  
                          and datediff(month, StatementOrRecptDate, '3-31-2018') >= 0 
                          and datediff(month, BeginDate, '3-31-2018') = 1)
from 
    BILLTRANSACTION 
where  
    (ClientID = 101383)  
    and datediff(month, EndDate, '3-31-2018') = 1

它有效 - 现在我正在尝试将它应用到我在 vb.net 中的代码,但它不起作用。

顺便说一句,我有一个本地 SQL Server Compact 数据库,我针对它运行查询,但它不起作用。

这是我的错误截图:https://ibb.co/fKBkHy

【问题讨论】:

  • 如果您 a) 显示您的 VB.NET 代码可能会有所帮助,因为错误可能就在其中,并且 b) 指定“不工作”,例如发布错误消息或描述与预期不同的意外行为。
  • 您好,请发布您的代码和您收到的错误代码
  • SQL Server 精简版supports only a subset of SQL Server T-SQL grammar。我怀疑SELECT 子句中的子查询是问题所在。

标签: sql sql-server vb.net sql-server-ce


【解决方案1】:

聚合中通常不允许子查询。因此,只需将表达式移至from 子句:

select (sum(bt.tax + bt.debit) + coalesce(bt2.tax_credit, 0))
from billtransaction bt cross join
     (select sum(bt2.tax + bt2.credit) as tax_credit
      from billtransaction bt2 
      where bt2.BillClass in (2, 5, 6) and
            ClientID = 101383 and  
            datediff(month, StatementOrRecptDate, '2018-03-31') >= 0 and
            datediff(month, BeginDate, '2018-03-31') = 1
     ) bt2
where bt.ClientID = 101383 and
      datediff(month, bt.EndDate, '2018-03-31') = 1;

注意事项:

  • 我添加了表别名和限定列名。当查询中有多个表引用时,您应该始终使用它们。
  • 我将日期格式固定为 ANSI/ISO 标准 YYYY-MM-DD 格式。
  • 我将ISNULL() 替换为COALESCE()。后者是 ANSI 标准。
  • 我将OR 表达式序列替换为IN——更易于编写、阅读和维护。

【讨论】:

  • @Gordin 它不起作用我尝试在 where 子句之前删除 bt2 中的 (.) 但它说无效的列名 'tax_credit'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多