因此,如何在用户声明的函数中使用诸如: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中像这样声明我的变量?
您正在创建内联表值函数,这种函数必须只包含一个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
如果要保持表函数内联,则可以使用公用表表达式来定义变量,如下所示:
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
)
)