我有一個名爲EmployeeTransfers的表EmpIdSSN,EmpBasePay,EmpTransferState和EmpFederalFilingStatus表。我創建的函數需要兩個參數,它們是狀態和歸檔狀態,因此它應該通過if語句並返回該代碼來確定代碼是什麼。我此刻的錯誤如下:如何創建一個函數以便從if語句返回一個字符?
消息444,級別16,狀態2,過程GetStateFilingStatus,6號線[批量起始行62]包含一個函數內不能將數據返回到客戶端Select語句。
我還遇到的其他問題是我想捕獲所有其他未包含在if語句中的狀態,以發送單一的通用代碼'S'和已婚的'M'。我試圖在最後做一個else語句,但不斷遇到各種錯誤。
create table EmployeeTransfers
(
EmpIdSSN char(9),
EmpBasePay decimal(16,4),
EmpTransferState char(2),
EmpFederalFilingStatus char(1)
)
GO
--Input data
insert into EmployeeTransfers
values
('555342121',60000.00, 'CA', 'S'),
('552342120',70000.00, 'NY', 'M'),
('552342120',87000.00, 'AZ', 'M'),
('456772332',55000.00, 'CT', 'S'),
('332223445',33000.00, 'NJ', 'M'),
('550667788',54000.00, 'DC', 'M')
GO
create function dbo.GetStateFilingStatus(@EmpFederalFilingStatus char(1), @EmpTransferState char(2))
returns char(1)
as
begin
declare @StateFilingStatus char;
select @StateFilingStatus
from EmployeeTransfers
where EmpFederalFilingStatus = @EmpFederalFilingStatus
and EmpTransferState = @EmpTransferState;
if (@EmpTransferState = 'MS') and (@EmpFederalFilingStatus = 'S')
set @StateFilingStatus = 'A';
else
set @StateFilingStatus = 'M';
return @StateFilingStatus;
if (@EmpTransferState = 'NJ') and (@EmpFederalFilingStatus = 'S')
set @StateFilingStatus = 'B';
else
set @StateFilingStatus = 'A';
return @StateFilingStatus;
if (@EmpTransferState = 'AZ') and (@EmpFederalFilingStatus = 'S')
set @StateFilingStatus = 'A';
else
set @StateFilingStatus = 'B';
return @StateFilingStatus;
if (@EmpTransferState = 'CT') and (@EmpFederalFilingStatus = 'S')
set @StateFilingStatus = 'F';
else
set @StateFilingStatus = 'M';
return @StateFilingStatus;
if (@EmpTransferState = 'DC') and (@EmpFederalFilingStatus = 'S')
set @StateFilingStatus = 'S';
else
set @StateFilingStatus = 'Y';
return @StateFilingStatus;
end;
go
什麼是你預期的結果? – McNets
@McNets用於輸出「StateFilingStatus = codeReturned」的函數。例如,如果輸入函數'NJ'和'S',它將返回代碼「B」。 – Danny
如錯誤所述,您正在執行此操作select @StateFilingStatus,但函數設計爲返回一個值,否則執行要返回的select語句。刪除該選擇 –