Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Look for trailing spaces in a table

I'd like to know how I can identify trailing spaces in a table. I'm using SQL Server 2008 and create the following table as a test

CREATE TABLE  first_test_name
   ( 
   firstName varchar(255)
    )

And then inserted a record like this:

insert into first_test_name (firstName)
values('Bob')

I then tried inserting a space and then adding a new record like this:

insert into first_test_name (firstName)
values('Bob ') -- just 1 space

And for a 3rd time,

insert into first_test_name (firstName)
values('Bob  ')   -- two spaces used this time.

Now if I query for for 'Bob' (no spaces), I still get a count of 3. My query was:

select count(*) from first_test_name WHERE firstName = 'Bob'

Shouldn't the answer have been 1?

Also, I used sp_help on this table and the value for "Trim Trailing Blanks" is set to no.

So why am I getting a count of 3? I was expecting just 1.

On a related note, if I search using this query

select * from first_test_name
where firstName like '% '

I then get the right answer of two rows found.

So just to reiterate, the question is why I get a count of 3 when searching for 'Bob'. Also, what does "Trim Trailing Blanks" mean in this case?

like image 716
Ray Avatar asked Oct 24 '25 14:10

Ray


1 Answers

Why I get a count of 3 when searching for 'Bob'?

SQL Server ignores trailing spaces in most string comparisons.

Also, what does "Trim Trailing Blanks" mean in this case?

This tells you the ANSI_PADDING option set when the table was created.

How can I identify those two with 1 or 2 trailing spaces?

Here's one way.

SELECT *
FROM first_test_name 
WHERE firstName LIKE 'Bob '

And to find ones with no trailing space

SELECT *
FROM first_test_name 
WHERE firstName LIKE 'Bob' AND firstName NOT LIKE 'Bob '
like image 75
Martin Smith Avatar answered Oct 27 '25 04:10

Martin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!