需要我創建的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'。您需要明確定義此參數的長度。 –