TSQL - char更改为INT

时间:2014-09-05 12:34:43

标签: sql sql-server tsql char

我需要变量@end_period是字符,例如01而不是1 以下代码有什么问题?

DECLARE @start_year AS CHAR(4)
DECLARE @end_year AS CHAR(4)
DECLARE @start_period AS CHAR(2)
DECLARE @end_period AS CHAR(2)
DECLARE @start_date as datetime
DECLARE @end_date as datetime

SET @start_year = '2014'
SET @end_year = '2014'
SET @start_period = '07'
SET @end_period = '08'

SET @end_year = CASE WHEN @end_period ='12' THEN @end_year + 1 ELSE @end_year END
SET @end_period = CASE WHEN @end_period ='12' THEN '01' ELSE @end_period + 1 END


select @end_year
select @end_period

3 个答案:

答案 0 :(得分:2)

使用CHAR有点奇怪。我不知道为什么,但是当我这样做时,我得到了你想要的结果:

DECLARE @start_year AS CHAR(4)
DECLARE @end_year AS CHAR(4)
DECLARE @start_period AS CHAR(2)
DECLARE @end_period AS CHAR(2)
DECLARE @start_date as datetime
DECLARE @end_date as datetime

SET @start_year = '2014'
SET @end_year = '2014'
SET @start_period = '07'
SET @end_period = '08'

SET @end_year = CASE WHEN @end_period ='12' THEN @end_year + 1 ELSE @end_year END
SET @end_period = CASE WHEN @end_period ='12' THEN '01' ELSE RIGHT('0'+CAST((@end_period + 1) AS varchar(2)) ,2) END


select @end_year
select @end_period

但是,当我更改此内容时:CAST((@end_period + 1) AS varchar(2))

对此:CAST((@end_period + 1) AS char(2))

我得到一个'9'而不是'09'。奇怪的。我不知道为什么。

编辑:神秘解决。

我不知道为什么我没有立刻想到这一点。实际上,我做到了。现在只有早上9点。

你看到的'9'实际上是'9'(9后面有一个空格)因为char(2)必须有2个字符。所以做正确('0'+'9')当然会返回'9'。你可以使用RTRIM()或REPLACE()来删除空格,如果你想要的话可​​以使用零,或者你可以使用我上面说明的varchar cast。

答案 1 :(得分:1)

当你这样做时:

@end_period + 1

示例:

'08'+1

字符串' 08'转换为整数8,添加一个,结果=> 9。 然后将隐式转换返回到char(2),即' 9'。

可以找到可能转换的完整矩阵(隐式或显式)on MSDN.


要解决您的问题,您可以通过以下方式添加前导零:

SET @end_period = CASE WHEN @end_period ='12' THEN '01' ELSE RIGHT('00' + CAST((@end_period + 1) as VARCHAR(2)), 2) END 

答案 2 :(得分:0)

尝试

SET @end_period = CASE WHEN @end_period = '12' THEN '01' 
                   ELSE CASE WHEN @end_period > 8 THEN CONVERT(VARCHAR,@end_period + 1) 
                             ELSE '0' + CONVERT(VARCHAR,@end_period + 1) 
                        END 
               END