first character replace in sql server

harinathu 6 Reputation points
2021-03-03T05:12:15.65+00:00

Hi I have one doubt in sql server.
how to replace only 1st character value when same character have multiple time.

CREATE TABLE [dbo].[productdetails](
[pid] [int] NULL,
[productName] varchar NULL
)
INSERT [dbo].[productdetails] ([pid], [productName]) VALUES (1, N'cinphol')
GO
INSERT [dbo].[productdetails] ([pid], [productName]) VALUES (2, N'apple')
GO
INSERT [dbo].[productdetails] ([pid], [productName]) VALUES (3, N'ppens')
GO
INSERT [dbo].[productdetails] ([pid], [productName]) VALUES (4, N'penrpos')
GO

based on above data I want output like below .
pid|productname
1 | cinZhol
2 |azple
3 |zpens
4 |zenrpos

select pid,replace(productname,'p','z')productname from productdetails

above query not giving expected result.
could you please tell me how to achive this task in sql server

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,828 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,559 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. MelissaMa-MSFT 24,176 Reputation points
    2021-03-03T05:31:58.333+00:00

    Hi @harinathu ,

    Welcome to Microsoft Q&A!

    Please refer below:

    select pid, SUBSTRING(productname,1,CHARINDEX('p',productname)-1) + 'z'+SUBSTRING(productname,CHARINDEX('p',productname)+1,len(productname)-CHARINDEX('p',productname)) productname  
    from productdetails  
    

    OR

    SELECT pid,STUFF(productname, CHARINDEX('p', productname), 1, 'z') productname FROM productdetails  
    

    Output:

    pid productname  
    1 cinzhol  
    2 azple  
    3 zpens  
    4 zenrpos  
    

    Best regards
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.