我如何将其转换为用户定义的函数?另外,我知道有几种类型的UDF ......在这种情况下哪一种最好?谢谢你的帮助。
SELECT TOP 10 ParkingSpotNumber
, count(*) as 'Usage'
FROM ParkingTransaction
GROUP BY ParkingSpotNumber
ORDER BY 'Usage' DESC
答案 0 :(得分:2)
由于您要返回多个列并且希望它是一个函数,因此您可以使用Table-Valued Function
:
create function Top_Parking_usage()
returns @ParkingCount table
(
ParkingSpotNumber int not null,
UsageCount int not null
)
as
BEGIN
INSERT INTO @ParkingCount(ParkingSpotNumber, UsageCount)
SELECT TOP 10 ParkingSpotNumber
, count(*) as 'Usage'
FROM ParkingTransaction
GROUP BY ParkingSpotNumber
ORDER BY 'Usage' DESC
RETURN
END;
GO
然后当你打电话时,你将使用:
select *
from dbo.Top_Parking_usage()
答案 1 :(得分:1)
尝试以下.....它会返回表格......
CREATE FUNCTION udf_GetParkingInfo()
RETURNS TABLE
AS
RETURN
(
SELECT TOP 10 ParkingSpotNumber
, count(*) as 'Usage'
FROM ParkingTransaction
GROUP BY ParkingSpotNumber
ORDER BY 'Usage' DESC
);
SELECT * from udf_GetParkingInfo()