从函数到临时表的多个选择

时间:2018-07-12 07:45:10

标签: sql sql-server union temp-tables sql-function

  • 我有一个要重用的功能helper_function
  • 将参数传递给另一个函数f_union_helper_functions,其中传递了具有ID的字符串id_string
  • 分割此字符串并遍历所有ID
  • 调用函数并将结果添加到临时表
  • 返回从此表中选择

伪代码:

create function f_union_helper_functions
(
@id_string varchar,
...
return table as
return
(
...
foreach id in @id_string
begin
   select * from helper_function(id) into #tmp
end
select #tmp
)

以上代码远非完整/正确。我只想将迭代和联合的概念合并到一个临时表中并返回它。我该如何实现?

1 个答案:

答案 0 :(得分:0)

这是我解决问题的方法:

ALTER FUNCTION [dbo].[f_union_helper_functions]
(
    @id_string NVARCHAR(1024)
)
RETURNS  TABLE 
AS 
RETURN
(
    SELECT * FROM [dbo].[fnSplit](@id_string, ',') c CROSS APPLY [dbo].[helper_function](c.item)
)

如果您的SQLServer> = 2016,则可以使用STRING_SPLIT代替[fnSplit],我从这里https://kishsharma.wordpress.com/2013/08/20/sql-server-user-defined-function-to-split-the-string-by-special-char/