【发布时间】:2015-10-11 18:25:54
【问题描述】:
需要有关我创建的 SQL 用户定义函数的帮助。 我的函数应该根据我给出的项目编号返回项目的类型。 当我执行该函数时,我得到一个错误
"子查询返回超过 1 个值。当 子查询遵循 =、!=、、>= 或当子查询用作 一个表达式。”
我想我应该将此函数的返回类型更改为表格。但是我不知道该怎么做。 这是我的功能:
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') --@item
set @MaxYear = (Select Max(m.year)
from mr m
where m.item_no = 'RR301') --@item
set @redoitem = (select redoitem
from mr m
where m.item_no = 'RR301') --@item
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 =@MaxYear -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 =@MaxYear -1 --2014
set @typeCount = @typeCount -1 --4
--return (@type)
END
END
END
return (@type)
END
我怎样才能让它工作?
【问题讨论】:
-
您的代码对于您给出的描述来说似乎太复杂了。但是带有子查询的第三个
set会导致您描述的错误。 -
您的循环看起来需要一个表值函数,这是一个标量函数,请参阅msdn.microsoft.com/en-us/library/ms186755.aspx
-
您需要一个多语句表值函数并从该函数返回一个表或使用具有多个 OUTPUT 参数的存储过程(首选)。此外,您的函数采用
varchar类型的参数,未定义任何长度,传递给此变量的任何内容都将被截断为默认长度1。您需要明确定义此参数的长度。
标签: sql sql-server function user-defined-functions