I've got this SQL query currently:
update con set lk = '' where datalength(lk) = 1 and lk = ' '
Is this the best query to convert any spaces (or other whitespace) to an empty string in MS SQL 2008 and above?
I've got this SQL query currently:
update con set lk = '' where datalength(lk) = 1 and lk = ' '
Is this the best query to convert any spaces (or other whitespace) to an empty string in MS SQL 2008 and above?
You can try trim()
:
update con
set lk = ltrim(rtrim(lk))
where ltrim(rtrim(lk)) <> lk;
That trims all values. You can instead do:
update con
set lk = ''
where lk not like '%[^ ]%'; -- put all "white space" characters here
You may use TRIM
for your case. Since you want to replace empty string so LTRIM
or RTRIM
both can work fine
update con set lk = '' where LTRIM(lk)=''
But if you have other then space
in your string then this will not work. For more advance method you need this.
update con set lk = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(1k, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')))
where LTRIM(RTRIM(REPLACE(REPLACE(1k, CHAR(13), ''), CHAR(9), '')))=''
Keeping in mind that the LEN
of any string made up of only spaces will be 0, you can do this (no trimming or replacing required):
UPDATE con SET lk = ''
WHERE LEN(lk) + PATINDEX('%[^'+CHAR(9)+CHAR(10)+CHAR(13)+']%',lk) = 0;
I included CHAR(9),10 & 11 in my code which is most common. You can get a complete list of Unicode whitespace characters here. If you are are dealing with VARCHAR you only need to worry about CHAR's less than 255: 9,10,11,12,13,32,133,160.