如果值是 1 个字符,如何使用填充函数将 0 附加到 SQL 服务器中的值

How to append 0 to a value in SQL Server if value is 1 character using Padding function

我有一个 returns YYYYMMDD 格式字符串的存储过程。

如果提供的字符串只有 1 个字符,我正在寻找创建 MM 和 DD 字符串的正确方法。

例如:

如果提供的天数为1,需要改为01,月份也一样。

declare @day as int
declare @month as int

select @day = 1
select @month = 9

Formatting code

select @day   // gives 01
select @month // gives 09

我不想在这里使用 if 逻辑来检查长度。是否可以使用某种 Formatting 功能来实现相同的结果?

我发现了类似的东西:

select right('0' + cast(@day as varchar(2)),2)

这是正确的解决方案吗?

您可以尝试以下方法。我知道你说过你不想使用 IF 语句,我可能会通过提供 CASE 语句来分裂头发,但是它是 IF:

的替代品
declare @day as int
declare @month as int

select @day = 1
select @month = 9

Formatting code

select CASE WHEN LEN(@day) = 1 THEN '0' + @day ELSE @day END   // gives 01
select CASE WHEN LEN(@month) = 1 THEN '0' + @month ELSE @month END // gives 09

您也可以试试:

declare @day as int
declare @month as int

select @day = 1
select @month = 9

Formatting code

select RIGHT('0'+cast(@day AS varchar(2)), 2)  // gives 01
select RIGHT('0'+cast(@day AS varchar(2)), 2) // gives 09

Would that be the correct solution?

它给了你想要的结果吗?那么是的,它是 one 解决方案。没什么错误

我会说存储过程似乎是这个函数的一个奇怪选择。存储过程通常用于return集合scalar function 可能是更好的选择。