是否可以在SQL中使用一个接受select Query结果的函数? 喜欢 SCalarFunc(从CustomQuery中选择*)
我还希望从函数中返回另一个选择查询吗?
任何人都可以提供样品吗?
答案 0 :(得分:2)
如果您使用的是SQL Server 2008
及以上版本,则可以使用User-Defined Table Types variable
-- Create first function to return the result of select query
create function fn_test()
returns table
as
return (select * from tab);
-- test it once
select * from dbo.fn_test()
--create a user defined table types
CREATE TYPE TableType
AS TABLE (id int not null,
name varchar(10));
--create your second level function passing the
--result of first function as table
CREATE FUNCTION fn_test_tab(@tabname TableType READONLY)
RETURNS VARCHAR(10)
AS
BEGIN
DECLARE @name VARCHAR(10)
SELECT @name = name FROM @tabname where id = 1;
RETURN @name
END
--define a variable of created table type
DECLARE @tab TableType;
-- fill the data from first function
insert into @tab select * from dbo.fn_test();
--call your second function passing the table variable
SELECT dbo.fn_test_tab(@tab);
旁注:在SQL server 2008 R2 Express
中测试,它运行正常。表类型概念的使用取自Pass table as parameter into sql server UDF