从用户定义的函数返回表,哪个最好?

时间:2016-02-15 10:08:51

标签: sql-server tsql user-defined-functions table-variable

我想知道从函数返回表格的更好做法是什么? 我应该定义表格结构还是使用RETURNS TABLE?使用这两种口味的场景是什么?

例如:

ALTER FUNCTION [dbo].[fnSplitIDs]
(
   @List VARCHAR(MAX)
)
RETURNS TABLE
AS
  RETURN ( 
    SELECT Item AS ID FROM
      ( SELECT Item = x.i.value('(./text())[1]', 'uniqueidentifier')
        FROM ( SELECT [XML] = CONVERT(XML, '<i>'
        + REPLACE(REPLACE(@List, ',', '</i><i>') , '''', '') + '</i>').query('.')
          ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
      WHERE Item IS NOT NULL
  );

对战:

ALTER FUNCTION [dbo].[fnSplitIDs]
(
   @List VARCHAR(MAX)
)
RETURNS @t TABLE([ID] uniqueidentifier)
AS
BEGIN
  INSERT INTO @t([ID])
  SELECT Item AS ID FROM
      ( SELECT Item = x.i.value('(./text())[1]', 'uniqueidentifier')
        FROM ( SELECT [XML] = CONVERT(XML, '<i>'
        + REPLACE(@List, ',', '</i><i>') + '</i>').query('.')
          ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
      WHERE Item IS NOT NULL
  RETURN
END

用法:

SELECT * FROM [dbo].[fnSplitIDs]('{ADD26A9A-ABDD-4755-9B3C-C4F12C46988F},{C9F92768-77F6-468B-A85C-4F42C2FDD6F6}')

0 个答案:

没有答案