创建用户定义的函数以返回包含客户信息的表?

时间:2019-02-12 00:58:22

标签: sql sql-server azure azure-sql-database

我正在尝试创建用户定义的函数,但我不断收到此错误消息:

Msg 102, Level 15, State 1, Procedure Huckestein_ufnCustomerDemographics, Line 2
Incorrect syntax near 'RETURNS'.

我已经研究了好几个小时,但仍无法弄清楚发生了什么...非常感谢任何建议。

这是我的SQL代码:

CREATE FUNCTION Huckestein_ufnCustomerDemographics 
RETURNS TABLE 
AS
RETURN
Select  CustomerID, FirstName, LastName, Phone, SalesLT.Address.*
From SalesLT.Customer, SalesLT.Address

2 个答案:

答案 0 :(得分:2)

请创建如下所示的函数:

CREATE FUNCTION Huckestein_ufnCustomerDemographics()
RETURNS TABLE 
AS
RETURN (
SELECT  C.CustomerID, C.FirstName, C.LastName, C.Phone, A.*
FROM SalesLT.Customer C INNER JOIN SalesLT.CustomerAddress AS CA  
        ON C.CustomerID = CA.CustomerID
     INNER JOIN SalesLT.[Address] A
        ON A.AddressID = CA.AddressID

);
GO

您可以如下所示对其进行测试:

SELECT * FROM Huckestein_ufnCustomerDemographics()

答案 1 :(得分:0)

尝试一下

CREATE FUNCTION Huckestein_ufnCustomerDemographics 
RETURNS TABLE 
AS
RETURN
(Select  CustomerID, FirstName, LastName, Phone, SalesLT.Address.*
From SalesLT.Customer, SalesLT.Address);

注意方括号和半冒号。 RETURNS TABLE创建一个内联表值函数。这意味着在return语句中包含单个选择