Wednesday, February 27, 2013

usage of Replace and Stuff in sql server

Hi,I want to share some info on which i have worked on

EX: if i have a column  Phonenumber Varchar(20) and i have the data as below

SELECT Phonenumber  from yourTablename
Phonenumber
123-456-7890
NULL
''
(123)-456-7890



To make it appear or convert to 1234567890
use Replace function available in SQL server ..



select Phonenumber , replace(replace(replace(replace(Phonenumber ,'(',''),')',''),'-',''), space(1),'')
as CleanedPhone  FROM  yourTablename


To update this to a table:

UPDATE  yourTablename
SET Phonenumber =   replace(replace(replace(replace(Phonenumber ,'(',''),')',''),'-',''), space(1),'')
GO


to revert back or make it as before :
Syntax:

--STUFF( textData, start , length , insertTextData ) 
UPDATE yourTablename
SET Phonenumber =
(SELECT STUFF ((STUFF (phone,4,0,'-' )),8,0,'-') )
GO

Thanks



No comments:

Post a Comment

https://blog.sqlauthority.com/2009/06/27/sql-server-fix-error-17892-logon-failed-for-login-due-to-trigger-execution-changed-database-context...