SQL - 添加Char(10)换行符

时间:2014-02-14 21:39:28

标签: sql-server tsql

(MS SQL only 2008R2) 我想知道如何在字符串中每次出现Char(10)之前和之后添加timestamp (##:##:##)换行符。

所以,如果我有一个"askdfjaksdfja asfd kj 03:56:34 sdfas 09:56:12 sdfa sd sss dg"的字符串,那么我希望所有##:##:##在每个timestamps之前和之后都有一个换行符。

{{1}}可以是任何时间,字符串可以是任何东西。

谢谢!

1 个答案:

答案 0 :(得分:1)

有一次?好的......继承人一枪。您可以将其包装在函数中并在表查询中使用它。您可能需要调整此项,具体取决于您要支持的边缘情况数量。您可以通过更改在@replace中暂存的数据集来完成此操作。

set nocount on;

declare @string varchar(max);
set @string = 'askdfjaksdfja asfd kj 03:56:34 sdfas 09:56:12 sdfa sd sss dg 42test x77:xx ';

declare @replace table (this char(4), that char(4));

with digits(NN) as
(
    select top 60 right('0'+cast(row_number() over(order by object_id)-1 as varchar), 2)
    from sys.all_columns --use your numbers table
)
insert into @replace
    --replace " NN:" with "char(10)+NN:"
    select  space(1)+NN+':',
            char(10)+NN+':'
    from    digits
    union all
    --replace ":NN " with ":NN+char(10)" 
    select  ':'+NN+space(1),
            ':'+NN+char(10)
    from    digits;

select  @string = replace(@string, this, that)
from    @replace
where   charindex(this, @string)>0;

select @string
相关问题