在UDF中声明表变量以输入表名作为参数

时间:2016-03-28 00:50:58

标签: sql sql-server tsql udf table-variable

我正在处理查询并创建了一个函数来从outcomes表中获取结果,并提供以下代码。

CREATE FUNCTION dbo.Shippad (@tbl NVARCHAR(30))
RETURNS TABLE
AS
    RETURN
      SELECT LEFT(ship, Charindex(' ', ship) - 1) + ' '
             + Replicate('*', Charindex(' ', Substring(ship, Charindex(' ', ship) + 1, Len(ship))) + 1 -2)
             + ' '
             + Reverse(LEFT(Reverse(ship), Charindex(' ', Reverse(ship)) - 1)) as final_work 
      FROM   outcomes
      WHERE  Charindex(' ', Substring(ship, Charindex(' ', ship) + 1, Len(ship))) > 1 

上述代码的问题在于,在执行期间输入的参数无关紧要,只要我输入的参数是数据库中的有效表名,它总是给出结果。

现在我想知道我是否可以创建一个参数来将表名输入FROM部分,这样只有当我输入outcomes时才显示结果。

我尝试使用以下代码声明表变量:

declare @ship_outcome table
(   final_work nvarchar(30)
)

insert into @ship_outcome (final_work)
select 
        left(ship, charindex(' ', ship) - 1) + ' ' + 
        replicate('*', charindex(' ', substring(ship, charindex(' ', ship) + 1, len(ship))) + 1 -2) + ' ' +
        reverse(left(reverse(ship), charindex(' ', reverse(ship)) - 1))
from outcomes
where charindex(' ', substring(ship, charindex(' ', ship) + 1, len(ship))) > 1;

select * from @ship_outcome

但是我不确定如何将表变量合并到UDF中。请帮忙。

1 个答案:

答案 0 :(得分:1)

您还可以使用多语句表值函数中的IF语句来实现结果,如下所述: -

CREATE FUNCTION dbo.Shippad (@tbl NVARCHAR(30))
RETURNS @t table
(final_work nvarchar(30))
AS
begin
if @tbl = 'outcomes'
begin
      Insert into @t
      SELECT LEFT(ship, Charindex(' ', ship) - 1) + ' '
             + Replicate('*', Charindex(' ', Substring(ship, Charindex(' ', ship) + 1, Len(ship))) + 1 -2)
             + ' '
             + Reverse(LEFT(Reverse(ship), Charindex(' ', Reverse(ship)) - 1)) as final_work 
      FROM   outcomes
      WHERE  Charindex(' ', Substring(ship, Charindex(' ', ship) + 1, Len(ship))) > 1 
end
return
end

注 - 多语句表值函数的性能对于大型记录来说是可怕的。建议使用@tbl ='结果'使用内联函数。在内联表值函数的where子句中,如 -

CREATE FUNCTION dbo.Shippad (@tbl NVARCHAR(30))
RETURNS TABLE
AS
    RETURN
      SELECT LEFT(ship, Charindex(' ', ship) - 1) + ' '
             + Replicate('*', Charindex(' ', Substring(ship, Charindex(' ', ship) + 1, Len(ship))) + 1 -2)
             + ' '
             + Reverse(LEFT(Reverse(ship), Charindex(' ', Reverse(ship)) - 1)) as final_work 
      FROM   outcomes
      WHERE  Charindex(' ', Substring(ship, Charindex(' ', ship) + 1, Len(ship))) > 1 and @tbl = 'outcomes'