1

这是我的查询

Create FUNCTION [dbo].[CountUses](@couponid INT)
RETURNS INT
AS
   BEGIN
   RETURN
    (
    SELECT  c.Id,
     c.Name,
     c.CreateDate,
     Count(cu.id) NofUses
  FROM   Coupon as  c
     JOIN CouponUse as cu
       ON c.id = cu.couponid
 GROUP  BY c.Id,
     c.Name,
     c.CreateDate
     )
 END 

它给出的错误Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.问题出在哪里?
除了主要答案,我也很感激您对优化我的查询的任何评论......

4

2 回答 2

1

如果您希望您的函数返回多个值,那么您需要查看Table-Valued Functions

这些类型的函数返回一个表而不仅仅是一个值。您当前的函数设置为标量函数,因此它只能返回一个值。

如果你想要一个标量值 - 让我们说count那么你的函数将类似于:

Create FUNCTION [dbo].[CountUses](@couponid INT)
RETURNS INT
AS
   BEGIN
   RETURN
    (
      SELECT Count(cu.id) NofUses  --- this can only return one column
      FROM   Coupon as  c
      JOIN CouponUse as cu
        ON c.id = cu.couponid
      WHERE cu.couponid = @couponid
     )
   END 

如果您打算返回一个数据表,那么您的函数将类似于:

Create FUNCTION [dbo].[CountUses](@couponid INT)
RETURNS @new_table table
(
  id int,
  name varchar(50),
  CreateDate datetime,
  NofUsers int
)
AS
BEGIN
  INSERT INTO @new_table
  SELECT c.Id,
       c.Name,
       c.CreateDate,
       Count(cu.id) NofUses
      FROM   Coupon as  c
      JOIN CouponUse as cu
        ON c.id = cu.couponid
      WHERE cu.couponid = @couponid
      GROUP  BY c.Id,  c.Name,  c.CreateDate

   RETURN
END
于 2012-11-21T11:13:45.877 回答
0

这将解决问题:

Create FUNCTION [dbo].[CountUses](@couponid INT)
RETURNS TABLE 
AS
RETURN
(
    SELECT  c.Id,
            c.Name,
            c.CreateDate,
            Count(cu.id) NofUses
    FROM   Coupon as  c
    JOIN CouponUse as cu
         ON c.id = cu.couponid
    GROUP  BY c.Id,
              c.Name,
              c.CreateDate
) 
于 2012-11-21T11:17:02.030 回答