这里有些奇怪的东西。我有一个名为FLDOC的数据库。它有一个名为SENTENCE的列,其中包含7个代表时间长度的数字。
example:
0050000
0750000
0000600
0040615
0000110
这7位数是一个类型的长度,因为数字代表YYYMMDD
所以我喜欢的是一个可以将其转换为这样的脚本:
5Y 00M 00D
75Y 00M 00D
6M (or 000Y 6M 00D is fine as well)
4Y 6M 15D etc etc
提前感谢...
答案 0 :(得分:2)
尝试此查询
select convert(varchar(10),left(example,3))+'Y '+
convert(varchar(10),Substring(example,4,3))+'M '+
convert(varchar(10),Right(example,3))+'D'+ from tablename
答案 1 :(得分:2)
您也可以使用Concat
执行此操作:
Select Concat
(
Left(SENTENCE, 3), 'Y ',
SubString(SENTENCE, 4, 2), 'M ',
Right(SENTENCE, 2), 'D'
)
From Table
要像在示例中那样压缩表达式,也可以使用它:
Select Concat
(
Case When (IsNumeric(Left(SENTENCE, 3)) = 1 And Left(SENTENCE, 3) <> '000')
Then Convert(Varchar (3), Convert(Int, Left(SENTENCE, 3))) + 'Y ' End,
Case When (IsNumeric(SubString(SENTENCE, 4, 2)) = 1 And SubString(SENTENCE, 4, 2) <> '00')
Then Convert(Varchar (2), Convert(Int, SubString(SENTENCE, 4, 2))) + 'M ' End,
Case When (IsNumeric(Right(SENTENCE, 2)) = 1 And Right(SENTENCE, 2) <> '00')
Then Convert(Varchar (2), Convert(Int, Right(SENTENCE, 2))) + 'D' End
)
From Table
答案 2 :(得分:2)
CONCAT
是SQL Server 2012的新功能。如果您有以前版本的SQL Server,您可以执行类似的操作来实现所需的输出:
SELECT sentence
,(
CASE
WHEN cast(left(sentence, 3) AS INT) > 0
THEN cast(cast(left(sentence, 3) AS INT) AS VARCHAR(3)) + 'Y '
ELSE cast(left(sentence, 3) AS VARCHAR(3)) + 'Y '
END +
CASE
WHEN cast(substring(sentence, 4, 2) AS INT) > 0
THEN cast(cast(substring(sentence, 4, 2) AS INT) AS VARCHAR(2)) + 'M '
ELSE cast(substring(sentence, 4, 2) AS VARCHAR(2)) + 'M '
END +
CASE
WHEN cast(right(sentence, 2) AS INT) > 0
THEN cast(cast(right(sentence, 2) AS INT) AS VARCHAR(3)) + 'D'
ELSE cast(right(sentence, 2) AS VARCHAR(3)) + 'D'
END
) AS new_sentence
FROM FLDOC;
<强>更新强>
要在评论中回答下面的问题,您可以写一个这样的更新声明:
update FLDOC
set sentence = (
CASE
WHEN cast(left(sentence, 3) AS INT) > 0
THEN cast(cast(left(sentence, 3) AS INT) AS VARCHAR(3)) + 'Y '
ELSE cast(left(sentence, 3) AS VARCHAR(3)) + 'Y '
END +
CASE
WHEN cast(substring(sentence, 4, 2) AS INT) > 0
THEN cast(cast(substring(sentence, 4, 2) AS INT) AS VARCHAR(2)) + 'M '
ELSE cast(substring(sentence, 4, 2) AS VARCHAR(2)) + 'M '
END +
CASE
WHEN cast(right(sentence, 2) AS INT) > 0
THEN cast(cast(right(sentence, 2) AS INT) AS VARCHAR(3)) + 'D'
ELSE cast(right(sentence, 2) AS VARCHAR(3)) + 'D'
END
)