我有一张看起来像那样的桌子
projectID , year , jan , feb , mar , apr , may ....
每个人都是一个数字库 并且我希望得到特定列的值,该值由发送给函数的值确定。
我有这个功能
CREATE FUNCTION [dbo].[func_]
( @BRANCH_ID NUMERIC(6,0) = 0,
@JOB_TYPE_ID NUMERIC(6,0) = 0,
@PROJECT_ID NUMERIC(6,0) = 0,
@MONTH_NAME varchar(10) = 0,
@YEAR_NUMBER NUMERIC(6,0) = 0)
RETURNS NUMERIC(6,1)
AS
BEGIN
DECLARE @FORCAST NUMERIC(6,1)
SELECT @FORCAST = @MONTH_NAME
FROM TABLE
WHERE Projectid = @PROJECT_ID
AND Year = @YEAR_NUMBER
IF @FORCAST IS NULL
RETURN(0)
RETURN(@FORCAST)
END
例如,如果我今天执行该函数并发送今天的年份和月份,它将返回“mar”列中的值。
答案 0 :(得分:0)
如果您的SQL Server版本中提供了UNPIVOT
(可从SQL Server 2005开始提供),则可以使用{{3}}:
SELECT @FORCAST = Forecast
FROM [TABLE] t
UNPIVOT (
Forecast FOR Month IN (jan, feb, mar, ...)
) u
WHERE Projectid = @PROJECT_ID
AND Year = @YEAR_NUMBER
AND Month = LEFT(@MONTH_NAME, 3)
否则它可能是这样的:
SELECT
@FORCAST = CASE @MONTH_NAME
WHEN 'January' THEN jan
WHEN 'February' THEN feb
WHEN 'March' THEN mar
...
END
FROM [TABLE]
WHERE Projectid = @PROJECT_ID
AND Year = @YEAR_NUMBER