Solved

sql string insert at position

Posted on 2012-03-26
4
330 Views
Last Modified: 2012-04-12
Is there any SQL funtion that allows me to insert a string at a specific position within a string?  As in if I have the string "Hello" Can I insert the text "y je"text specifically at position 3 to achieve the result "Hey jello"
0
Comment
Question by:zintech
  • 2
4 Comments
 
LVL 2

Expert Comment

by:dantheanswerman
ID: 37768178
0
 
LVL 9

Expert Comment

by:OCDan
ID: 37768305
Although STUFF is very useful and well worth reading about, it REPLACES characters instead of just inserting in the desired place.

Here are a couple of ways to do it, CHARINDEX is more flexible here and you can change it as you to insert after whatever character/sequence you want.:

declare @string varchar(200)
set @string = 'hello'

select left(@string,2)+'y je'+ right(@string,3)

--OR

select substring(@string,0, len(@string)-charindex( 'e',@string)) + 'y je' + substring(@string, charindex( 'e',@string)+1,len(@string))

Open in new window

0
 
LVL 75

Accepted Solution

by:
Anthony Perkins earned 500 total points
ID: 37769531
>>it REPLACES characters instead of just inserting in the desired place.<<
Actually that is not true.  It can insert.  You may want to re-read the documentation or see for yourself:
DECLARE @Value varchar(20) = 'Hello'
SELECT STUFF(@Value, 3, 0, 'y je')

Open in new window

Output:
Hey jello
0
 
LVL 9

Expert Comment

by:OCDan
ID: 37769948
My bad, thanks acperkins
0

Featured Post

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how the fundamental information of how to create a table.

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question