ajdeguzman
ajdeguzman

Reputation: 1209

How to insert character in between a string in SQL Server 2008?

I need help in inserting a character inside a string, e.g.:

031613 05:39 AM

The output should be:

03/16/13 05:39 AM

Upvotes: 15

Views: 43179

Answers (3)

DurGesh kuMar RAO
DurGesh kuMar RAO

Reputation: 284

use can also do like this.. but quite big solution.

declare @T varchar(100)= '031613 05:39 AM'
declare @result varchar(100) =''

;with CTE
as
(
Select 0 as startIndex, 2 as endIndex 
union all
select convert(int, endIndex) as startIndex , endIndex+2 as endIndex from CTe where endIndex < charindex(' ',@T)
)
select top 3 @result += substring(@T,startIndex+1, endIndex-startIndex)+'/' from CTe
select substring( @result,0,len(@result))

Upvotes: 0

Nenad Zivkovic
Nenad Zivkovic

Reputation: 18559

You can use STUFF

DECLARE @String NVARCHAR(20) = '031613 05:39 AM'

SELECT STUFF(STUFF(@String,3,0,'/'),6,0,'/')

Fiddle

Upvotes: 32

Adriaan Stander
Adriaan Stander

Reputation: 166396

How about using SUBSTRING?

DECLARE @String VARCHAR(50) = '031613 05:39 AM'

SELECT  @String,
        SUBSTRING(@String,1,2) + '/' + SUBSTRING(@String,3,2) + '/' + SUBSTRING(@String,3,2) + SUBSTRING(@String,7,LEN(@String)-6)

SQLFiddle DEMO

Upvotes: 1

Related Questions