是否可以根据另一个参数的指定值计算参数值?

时间:2013-12-04 00:08:23

标签: sql sql-server tsql parameters dynamic-sql

是否可以在SQL中创建动态参数?也就是说,基于分配给另一个参数的值进行计算。例如,我正在将值传递到我的存储过程中,如下所示:

       IF (@SP_Season = 'F13')
        Begin
        Set @PriorSeason_2012 = 'F12'
        Set @PriorSeason_2011 = 'F11'
        END

   IF (@SP_Season = 'F14')
    Begin
    Set @PriorSeason_1 = 'F13'
    Set @PriorSeason_2012 = 'F12'
    END

   IF (@SP_Season = 'F15')
    Begin
    Set @PriorSeason_1 = 'F14'
    Set @PriorSeason_2 = 'F13'
    END

可以计算@ PriorSeason_1和@ PriorSeason_2值,以便将参数设置为与此类似吗?

   SET @SP_Season = 'F13'
   SET @PriorSeason_1 = (@SP_Season - 1)
   SET @PriorSeason_2 = (@SP_Season - 2)

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

DECLARE @var VARCHAR(3) = 'F14'
SELECT SUBSTRING(@var, 1, 1)
SELECT SUBSTRING(@var, 1, 1) + CAST(CAST(SUBSTRING(@var, 2, LEN(@var) - 1) AS INT) - 1 AS VARCHAR)
SELECT SUBSTRING(@var, 1, 1) + CAST(CAST(SUBSTRING(@var, 2, LEN(@var) - 1) AS INT) - 2 AS VARCHAR) 

答案 1 :(得分:0)

感谢您的帮助,但像往常一样,我在提问后不久就明白了。

现在,当报告的用户选择要显示的适当季节时,前几年将根据用户输入计算。

Declare @SP_Season varchar(50) = @Season 
Declare @PriorSeason_1 varchar(50)
Declare @PriorSeason_2 varchar(50)
Declare @YR numeric 
Declare @Sport varchar (50)

SET @YR = (SELECT RIGHT (SEASON,2) FROM TK_SEASON WHERE SEASON = @SP_Season)
SET @Sport = (SELECT SUBSTRING(SEASON,1,LEN(SEASON)-2) FROM TK_SEASON WHERE SEASON = @SP_Season)
SET @PriorSeason_1 = (@Sport + CONVERT(VARCHAR(100),@YR - 1))
SET @PriorSeason_2 = (@Sport + CONVERT(VARCHAR(100),@YR - 2))