Groups | Blog | Home
all groups > sql server (alternate) > november 2006 >

sql server (alternate) : LEFT and string function



othellomy NO[at]SPAM yahoo.com
11/3/2006 2:45:44 AM
select left('Hello World /Ok',charindex('/','Hello World /Ok')-1)
Hello World
That works fine.

However I got an error message:
select left('Hello World Ok',charindex('/','Hello World Ok')-1)
Instead of:
'Hello World Ok'

I get:
Server: Msg 536, Level 16, State 3, Line 1
Invalid length parameter passed to the substring function.

Microsoft Doc incorrectly says:
"LEFT ( character_expression , integer_expression )
integer_expression
Is a positive whole number. If integer_expression is negative, a null
string is returned."

Is there an easier solutoin using left or any other string function
instead of using a case statement?
Also, charindex('/','Hello World Ok') should return NULL instead 0 so
that we can use isnull function.
Thanks.
Hugo Kornelis
11/3/2006 11:28:51 PM
[quoted text, click to view]

(snip)
[quoted text, click to view]

Hi othellomy,

Your copy of Books Online must be outdated, then. Here's what my version
says:

"integer_expression

"Is a positive integer that specifies how many characters of the
character_expression will be returned. If integer_expression is
negative, an error is returned. integer_expression can be of
type bigint."

[quoted text, click to view]

You can use NULLIF to change the 0 to NULL yourself:

SELECT LEFT ('Hello World Ok',
NULLIF (CHARINDEX('/','Hello World Ok'), 0) - 1);

--
othellomy NO[at]SPAM yahoo.com
11/5/2006 8:04:48 PM
Thanks :)

[quoted text, click to view]
AddThis Social Bookmark Button