简体   繁体   中英

Microsoft SQL Server treats leading and trailing whitespaces differently?

I observe that sql is able to match a value like '4280 ' if matched for '4280' but it does not detect ' 10442', when searched for 10442

Please see the queries below

CREATE TABLE Persons
(
PersonID int,
myval varchar(255),
);

select * from Persons

insert into Persons values(1,'aftab')
insert into Persons values(2,'    10442')
insert into Persons values(3,'4280 ')

/* It does not retrieve the row which has myal '10442' */
select * from Persons where myval='10442'

/* It does retrieve the row which has myal '4280' in spite of the trailing spaces*/
select * from Persons where myval='4280'

I would have expected both the trailing and leading white spaces to be treated the same, ie, either ' 10442' and '4280 ' are both detected, or both to be not detected.

Use a Left Trim and Right trim to remove spaces on both ends

select * from Persons where LTRIM(RTRIM(myval))='10442'

The Best way to do this is to restrict such data with white spaces to be getting added into your DB tables. I Hope you are using Oracle as your DB, data with whitespace will act weird in case if you try to retrieve.

Solution:

    Insert into Persons values(rtrim(ltrim(myval)));

2) Else if you have data with such white spaces already, i would recommend you to add trim function while retrieval, so as to avoid weird outputs.

I hope this might help you a bit.

-Bruce

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM