子查询返回的值超过1。当子查询遵循=,!=,<,<=,>,> =或

时间:2019-11-15 17:32:20

标签: sql sql-server

create FUNCTION GetProductPercity(@CityName nvarchar(50))
RETURNS @returntable TABLE 
(
    [productName] nvarchar(50),
    [Quantity] int
)
AS
BEGIN
    declare @title nvarchar(50)
    declare @quantity int

    IF( @cityName in (select s.City from Suppliers s) )
    BEGIN
        set @title = (
            select  p.ProductName 
            from Suppliers s  right join Products p 
                 on s.SupplierID = p.SupplierID
            where s.City = @CityName
        )

        set @quantity = (
            select  count(p.ProductID)
            from Suppliers s  right join Products p 
                 on s.SupplierID = p.SupplierID
            where s.City = @CityName
        )

        insert into @returntable([productName],[Quantity])
        values(@title,@quantity)
    END
    --INSERT @returntable
    --SELECT @CityName, @param2
    RETURN
END
select * from dbo.GetProductPercity('london')

我收到以下错误:

  

信息512,级别16,状态1,第126行
  子查询返回的值超过1。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。

2 个答案:

答案 0 :(得分:1)

通过将其转换为内联表值函数,可以大大简化此过程。它不仅可以解决您的错误,而且可以提供更好的性能并减少很多代码。我只是不太了解您最初的RIGHT加入的意义。我假设您想要给定城市的供应商数量。扭转这一点,使“产品”成为主表。并将您的联接更改为内部联接。

create FUNCTION GetProductPercity
(
    @CityName nvarchar(50)
)RETURNS TABLE AS RETURN
    select p.ProductName
        , Quantity = count(*)
    from Products p
    join Suppliers s on s.SupplierID = p.SupplierID
    where s.City = @CityName

答案 1 :(得分:0)

尝试

create FUNCTION GetProductPercity 
(
   @CityName nvarchar(50) 
) 
RETURNS @returntable TABLE 
( [productName] nvarchar(50), [Quantity] int ) 
AS
BEGIN 

INSERT into @returntable([productName],[Quantity]) 
SELECT p.ProductName , count(p.ProductID) 
 FROM Suppliers s 
 inner join Products p on s.SupplierID = p.SupplierID 
 WHERE s.City = @CityName
 return
END