【问题标题】:SQL Function not returning the same as normal querySQL 函数返回的结果与普通查询不同
【发布时间】:2012-12-13 15:20:11
【问题描述】:

我正在使用SQL Server 2008R2,并且我有以下脚本。

select * from orderSummaryTotal(@orderid,@sessionid)

select
    count(*) as Quantity,
    IsNull(Sum(VatAmount),0) As VATAmount,
    IsNull(Sum(NetAmount),0) As NetAmount,
    IsNull(Sum(GrossAmount),0) as GrossAmount
from tbOrderProduct
where
     Orderid = @orderid
 and sessionid = @sessionid

当我运行第二个查询时,它会返回值。即数量为3

但是,当我运行第一个查询时,它返回的数量为 0。

第一个查询是一个表值函数这是代码。

ALTER FUNCTION [dbo].[OrderSummaryTotal](@orderid varchar, @sessionid uniqueidentifier)
RETURNS TABLE as
RETURN
  select
      count(*) as Quantity,
      IsNull(Sum(VatAmount),0) As VATAmount,
      IsNull(Sum(NetAmount),0) As NetAmount,
      IsNull(Sum(GrossAmount),0) as GrossAmount
  from tbOrderProduct
  where
       Orderid = @orderid
   and sessionid = @sessionid

两个查询是相同的,但为什么一个返回计数 3 而另一个不返回?有什么想法吗?

【问题讨论】:

  • 你能把tbOrderProduct的名字在两个地方都变成Database.Schema.tbOrderProduct吗?你仍然得到不同的答案吗?
  • 如何在没有模式限定符的情况下使用表值函数?

标签: sql count sql-server-2008-r2 user-defined-functions


【解决方案1】:

原因是你的函数定义中有varchar,没有长度。

尝试将其更改为 varchar(8000) 之类的名称,或者一个足以满足您需要的数字。

【讨论】:

  • 或者最好与Orderid完全相同的类型和长度。 :)
猜你喜欢
  • 1970-01-01
  • 2020-10-17
  • 2017-01-16
  • 2012-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
相关资源
最近更新 更多