Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Problem with Where condition in query.
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

2 Posts

Posted - 03/27/2013 :  17:45:16  Show Profile  Reply with Quote
If I run the following query, I get results without issue:

select Firstname, right(Firstname,(CHARINDEX(' ', reverse(FirstName))-1)), len(right(Firstname,(CHARINDEX(' ', reverse(FirstName))-1))) from Customers

However if I run this query:

select * from customers where len(right(Firstname,(CHARINDEX(' ', reverse(FirstName))-1))) > 15

I get this error:
Invalid length parameter passed to the RIGHT function.State: 42000, Native: 536, Source: Microsoft SQL Native Client

Could someone illuminate me on the problem and point me towards a solution.

Thank you.

Patron Saint of Lost Yaks

30421 Posts

Posted - 03/27/2013 :  17:52:32  Show Profile  Visit SwePeso's Homepage  Reply with Quote
Most probably with a first name that does not have a space. Then CHARINDEX returns 0 and substraction 1 gives -1, and this value is invalid for substring/left/right function.

N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

James K
Flowing Fount of Yak Knowledge

3873 Posts

Posted - 03/27/2013 :  18:05:49  Show Profile  Reply with Quote
To add to what SwePeso said, your first query is not showing an error probably because you have (some other) where clause that happens to eliminate all firstnames without spaces in them.
Go to Top of Page

Flowing Fount of Yak Knowledge

4614 Posts

Posted - 03/27/2013 :  18:25:44  Show Profile  Reply with Quote
Originally posted by Adstra

Could someone illuminate me on the problem and point me towards a solution.

DECLARE @FirstName VARCHAR(100) = 'Test';

-- Error
select len(right(@FirstName,(CHARINDEX(' ', reverse(@FirstName))-1)))

--One solution - check for a charindex value of 0.
select len(right(@FirstName,(NULLIF(CHARINDEX(' ', reverse(@FirstName)), 0) -1)))
Go to Top of Page

Starting Member

2 Posts

Posted - 03/28/2013 :  10:36:57  Show Profile  Reply with Quote
Thank you, I found the problem I had 1 record return a zero.
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.04 seconds. Powered By: Snitz Forums 2000