我正在编写一个返回排序列表的第一个值的SQL函数,但我真的不知道如何启动?该函数只有一个参数,即列表编号(VRI.Listing_Number
)
使用select
语句,我有:
SELECT TOP 1
--VRI.Listing_RID, VRI.Listing_Number, VRI.Listing_Price, CH.Old_Price, CH.Date_Time_Changed
CH.Old_Price
FROM dbo.View_Report_Information_Tables VRI WITH (NOLOCK)
INNER JOIN dbo.MLS_Change_History CH WITH (NOLOCK) ON
VRI.Listing_RID = CH.Listing_RID
INNER JOIN dbo.MLS_Change_History_Type CHT WITH (NOLOCK) ON
CH.Transaction_RID = CHT.Transaction_RID
WHERE CHT.Change_Type_Display = 3 AND
VRI.Listing_RID = CH.LISTING_RID
ORDER BY CH.Transaction_RID DESC
此sql查询从价格列表中返回最后的价格变化。
我是sql的新手,所以我甚至不太了解语法。例如,我查找了CH.Old_Price
,我看到它TYPE_NAME
是numeric
,但它也有长度和精度,比例......这个函数的返回值应该是多少? ?
有什么想法吗?
谢谢,
答案 0 :(得分:1)
假设您发布的select
语句返回正确的数据,函数的语法相当简单:
CREATE FUNCTION <Inline_Function_Name, sysname, FunctionName>
(
-- Add the parameters for the function here
@Listing_Number int,
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
)
您也可以通过右键点击SSMS中的Functions
来获取此信息 - &gt;对象资源管理器 - &gt; - &GT;可编程性并选择正确的功能类型。我上面的示例假定这返回整行数据(似乎是这种情况)。我还假设VRI.Listing_Number
是一个int。
答案 1 :(得分:1)
CREATE FUNCTION dbo.FirstPriceChange(@Listing_Number int)
RETURNS MONEY
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN
RETURN (
SELECT TOP 1
CH.Old_Price
FROM dbo.View_Report_Information_Tables VRI WITH (NOLOCK)
INNER JOIN dbo.MLS_Change_History CH WITH (NOLOCK) ON
VRI.Listing_RID = CH.Listing_RID
INNER JOIN dbo.MLS_Change_History_Type CHT WITH (NOLOCK) ON
CH.Transaction_RID = CHT.Transaction_RID
WHERE CHT.Change_Type_Display = 3 AND
VRI.Listing_RID = CH.LISTING_RID AND
VRI.Listing_Number = @Listing_Number
ORDER BY CH.Transaction_RID DESC
)
END
GO
样本用法:
SELECT
VRI.Listing_RID, VRI.col1, VRI.Col2,
dbo.FirstPriceChange(VRI.Listing_Number) AS FirstPriceChange
FROM dbo.View_Report_Information_Tables VRI
注意:
RETURNS MONEY
它会返回一种货币类型WITH RETURNS NULL ON NULL INPUT
如果输入为null,则返回null 答案 2 :(得分:0)
SELECT TOP 1 FROM (
SELECT *
FROM dbo.View_Report_Information_Tables VRI WITH (NOLOCK)
INNER JOIN dbo.MLS_Change_History CH WITH (NOLOCK) ON
VRI.Listing_RID = CH.Listing_RID
INNER JOIN dbo.MLS_Change_History_Type CHT WITH (NOLOCK) ON
CH.Transaction_RID = CHT.Transaction_RID
WHERE CHT.Change_Type_Display = 3 AND
VRI.Listing_RID = CH.LISTING_RID
ORDER BY CH.Transaction_RID DESC
) AS `aaa`