SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

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

Adstra
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.

SwePeso
Patron Saint of Lost Yaks

Sweden
30281 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

3742 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

Lamprey
Flowing Fount of Yak Knowledge

4614 Posts

Posted - 03/27/2013 :  18:25:44  Show Profile  Reply with Quote
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

Adstra
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  
 New 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.08 seconds. Powered By: Snitz Forums 2000