返回函数中的表

时间:2011-06-20 09:51:48

标签: sql-server tsql

CREATE FUNCTION dbo.GetCustomers
(
  @ZIPCodePattern VARCHAR(255)
)
RETURNS TABLE(How i return as dbo.Customers)

AS BEGIN
manipulating ZIPCodePattern ...
SELECT * FROM dbo.Customers
WHERE dbo.RegExFunctionMatch(dbo.Customers.ZIPCODE, @ZIPCodePattern ) = 1
RETURN(How i retrun all where my function returns 1) 
END

此函数必须返回ZIPCODE匹配模式的所有dbo.Customers行。 我在比较它之前操纵var ZIPCodePattern。 我不熟悉语法。请帮忙。

1 个答案:

答案 0 :(得分:2)

请参阅Create Function in MSDN

您需要为单个语句选择执行类似的操作:

CREATE FUNCTION dbo.GetCustomers
(
  @ZIPCodePattern VARCHAR(255)
)
RETURNS TABLE

AS 

RETURN
(
-- manipulating ZIPCodePattern ...
SELECT * FROM dbo.Customers
WHERE dbo.RegExFunctionMatch(dbo.Customers.ZIPCODE, @ZIPCodePattern ) = 1
);
GO

或者如果您使用多个SQL语句,则需要明确定义表结构:

CREATE FUNCTION dbo.GetCustomers
(
  @ZIPCodePattern VARCHAR(255)
)
RETURNS @TableToReturn TABLE
(
-- Define your table structure here
CustomerId int primary key not null,
CustomerName varchar(200) not null,
-- ...

) 

AS 
BEGIN

-- Do some stuff with your @ZipPattern
if (@ZipPattern != Null)
begin

 -- do something

end


Insert Into @TableToReturn 
SELECT * FROM dbo.Customers
WHERE dbo.RegExFunctionMatch(dbo.Customers.ZIPCODE, @ZIPCodePattern ) = 1



Select * From @TableToReturn


END
GO