Microsoft tql如何在用户定义的函数中声明临时变量?

时间:2014-07-02 09:07:11

标签: sql tsql sql-server-2014

那么如何在用户声明的函数中声明一个像:declare @tempVar varchar(max)声明的临时局部变量? 我试图解决的实际问题是在用户定义的存储函数中声明和使用变量。我声明我的功能如下:

create function someFunction(@someParam varchar(100))
returns table
as 
return (
    declare @tempvar varchar(100)
    set @tempvar = ''--Set the var to something useful
    select * from sometable where somecolumn = (
        select top 1 someColumn
        from sometable
        where somecolumn = @tempvar
    )
)

服务器抱怨在错误的地方声明变量。我应该在哪里用UDF声明我的变量?

2 个答案:

答案 0 :(得分:3)

您正在创建内联表值函数,此类函数必须只包含一个SELECT语句。

如果要使用变量,则必须创建多语句表值函数。您的函数将声明为:

create function someFunction(@someParam varchar(100))
returns @table (field1 type, field2 type, ...)
as 
begin
    declare @tempvar varchar(100)
    set @tempvar = ''--Set the var to something useful
    insert @table
    select * from sometable where somecolumn = (
        select top 1 someColumn
        from sometable
        where somecolumn = @tempvar
    )
    return
end

答案 1 :(得分:0)

如果要保持表函数内联,可以使用公用表表达式来定义变量,如下所示:

create function someFunction(@someParam varchar(100))
returns table
as 
return (
  WITH cte (tempvar) AS
    (
    SELECT '' -- Set the var to something useful
    )
    select * from sometable where somecolumn = (
        select top 1 someColumn
        from sometable
          JOIN cte ON 1=1
        where somecolumn = cte.tempvar
    )
)