需要我创建的SQL user_defined函数的帮助。 我的函数应该根据我给的项目编号返回项目的类型。 当我执行的功能我得到一个错误如何从SQL中的用户定义函数返回多个值
“子查询返回多个值,这是不允许的 当子查询跟随=,!=,<,< =,>,> =或当子查询用作 的表达式。“
我想我应该将此函数返回类型更改为表。但是我不知道该怎么做。 这里是我的功能:
create function [dbo].[fx_calculate_type](@item varchar)
returns varchar(10)
AS
begin
DECLARE @type VARCHAR(10)
,@typeCount int
,@MaxYear int
,@redoitem varchar(18)
set @type = ''
set @typeCount = (Select count(m.year)
from mr m
where m.item_no = 'RR301') [email protected]
set @MaxYear = (Select Max(m.year)
from mr m
where m.item_no = 'RR301') [email protected]
set @redoitem = (select redoitem
from mr m
where m.item_no = 'RR301') [email protected]
if (@redoitem is null or @redoitem= '')
BEGIN
While (@typeCount>=1)
Begin
Continue
If @typeCount = 1
Begin
set @type = 'N'
--return (@type)
End
Else
Begin
set @type = @typeCount+ 'C'
set @MaxYear [email protected] -1 --2014
set @typeCount = @typeCount -1 --4
-- return (@type)
END
END
END
Else
BEGIN
While (@typeCount>=1)
Begin
Continue
If @typeCount = 1
Begin
set @type = 'N'
--return (@type)
End
Else
Begin
set @type = @typeCount+ 'R'
set @MaxYear [email protected] -1 --2014
set @typeCount = @typeCount -1 --4
--return (@type)
END
END
END
return (@type)
END
我怎样才能使它发挥作用?
你的代码看起来太复杂了你给的描述。但是第三个带有子查询的'set'会导致你描述的错误。 –
您的循环看起来像您需要有一个表值函数,这是一个标量函数,请参阅https://msdn.microsoft.com/en-us/library/ms186755.aspx –
您需要一个多语句表值函数并从该函数返回一个表或使用具有多个OUTPUT参数(首选)的存储过程。另外你的函数在没有定义任何长度的情况下接受'varchar'类型的参数,传递给这个变量的任何东西都会被截断为默认长度'1'。您需要明确定义此参数的长度。 –