Find and replace query in SQL server

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pdeepti
    New Member
    • Apr 2014
    • 2

    Find and replace query in SQL server

    I want to chane my name column records like if the name is with one word (Example: John) it shuold remain same (Ex: John). If it is with two words (Ex: John Bodi) it should be there as it is (Ex: John Bodi) but if it is one word and one letter (Ex:John B) then it should get '.' at the end of the letter(Ex: John B.)
    Please post your query for this. It helps me.
  • landrew21
    New Member
    • Apr 2014
    • 2

    #2
    Hi,
    Try this:
    Code:
    CREATE TABLE dbo.tblNames 
    (
    	ID int,
    	FName varchar(25),
    	LName varchar(25)
    ) 
    GO
    
    INSERT INTO tblNames 
     	VALUES (1, 'John', 'Doe')
    INSERT INTO tblNames 
     	VALUES (2, 'Jack', 'B')
    INSERT INTO tblNames 
     	VALUES (3, 'S', 'Fry')
    INSERT INTO tblNames 
     	VALUES (4, 'H', 'M')
    GO
    
    SELECT * FROM tblNames
    GO
    	
    UPDATE tblNames SET 
    	FName = CASE WHEN LEN(FName) = 1 THEN (FName + '.') ELSE FName END,
    	LName = CASE WHEN LEN(LName) = 1 THEN (LName + '.') ELSE LName END
    GO
    
    SELECT * FROM tblNames
    
    GO
    DROP TABLE tblNames

    Comment

    • pdeepti
      New Member
      • Apr 2014
      • 2

      #3
      Thank you so much! It helped me alot.

      Originally posted by landrew21
      Hi,
      Try this:
      Code:
      CREATE TABLE dbo.tblNames 
      (
      	ID int,
      	FName varchar(25),
      	LName varchar(25)
      ) 
      GO
      
      INSERT INTO tblNames 
       	VALUES (1, 'John', 'Doe')
      INSERT INTO tblNames 
       	VALUES (2, 'Jack', 'B')
      INSERT INTO tblNames 
       	VALUES (3, 'S', 'Fry')
      INSERT INTO tblNames 
       	VALUES (4, 'H', 'M')
      GO
      
      SELECT * FROM tblNames
      GO
      	
      UPDATE tblNames SET 
      	FName = CASE WHEN LEN(FName) = 1 THEN (FName + '.') ELSE FName END,
      	LName = CASE WHEN LEN(LName) = 1 THEN (LName + '.') ELSE LName END
      GO
      
      SELECT * FROM tblNames
      
      GO
      DROP TABLE tblNames

      Comment

      Working...