当未使用EXISTS引入子查询时,只能在选择列表中指定一个表达式

时间:2012-11-21 11:10:07

标签: sql sql-server sql-server-2008 tsql

这是我的查询

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.问题在哪里?
除了主要答案,我还要感谢您对优化我的查询的任何评论...

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
)