June 20, 2006 at 3:07 am
Hi,
I am using a query :
select len(' ')
string contains blank spaces but it returns 0 length to me.
Have you any idea to correct this query ?
Regards,
Amit Gupta
June 20, 2006 at 3:25 am
It's how len() works with spaces. You can use datalength() instead for your purpose.
select len(' '), datalength(' ')
----------- -----------
0 6
(1 row(s) affected)
/Kenneth
June 20, 2006 at 3:43 am
Kenneth...
Thank you so much..
June 20, 2006 at 4:59 am
No offense, but it is how SQL treats trailing spaces, not leading spaces.
select len(' g'),
datalength(' g'),
len('G '),
datalength('G ')
-- -- -- --
6 6 1 6
N 56°04'39.16"
E 12°55'05.25"
June 20, 2006 at 6:13 am
And you have to divide the datalength() output by 2 for unicode (nchar etc.) strings.
Tim Wilkinson
"If it doesn't work in practice, you're using the wrong theory"
- Immanuel Kant
June 20, 2006 at 7:03 am
You're correct Peter.
However, the question seemed to be how to count how many spaces there was in a space-only string.
The notion of dividing by two if there's a unicode string is a good one. Didn't think of that
/Kenneth
June 21, 2006 at 10:30 am
if you don't want the worry of Datalength and remembering the the division by 2 for NVarchars, but you want an accurate length that includes trailing spaces, why not simply use the replace function to change the spaces to something else? Then, if the variable gets changed to something else like a varchar, and you forget the division by 2 you don't hit errors.
Declare @stringWithTrailingBlanks nvarchar(255)
Select @stringWithTrailingBlanks=' '
select len(replace(@stringWithTrailingBlanks,' ','|'))
June 26, 2006 at 10:02 am
June 26, 2006 at 11:29 am
Nice! Let's only hope that the first sequence of spaces does not equal 8000 spaces. Because that will produce the result of -1.
N 56°04'39.16"
E 12°55'05.25"
June 26, 2006 at 11:31 am
And divide that by 2 for unicode strings!
Tim Wilkinson
"If it doesn't work in practice, you're using the wrong theory"
- Immanuel Kant
June 27, 2006 at 2:28 am
I thought you only had to divide by 2 when using datalength.
June 27, 2006 at 4:54 am
Yes, sorry, not clear. I was referring to the maximum capacity of 8000, as mentioned in the post above.
The point being that insofar as you need to avoid overflow, you still have to shoulder the (supposedly very onerous!) burden of remembering what kind of data you are using.
Tim Wilkinson
"If it doesn't work in practice, you're using the wrong theory"
- Immanuel Kant
Viewing 12 posts - 1 through 11 (of 11 total)
You must be logged in to reply to this topic. Login to reply