Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Could you help

records in name are like
ANTOWYN PEARSON
XUAN THI HA
DARRIN HAALA
BENJAMIN HAAS
KALIM HABET

What I have tried:

------------------------------------------------------
select left(name,CHARINDEX(' ',name)-1) as first_name from Business
-----------------------------------------------------------------
but getting error:
Msg 537, Level 16, State 2, Line 18
Invalid length parameter passed to the LEFT or SUBSTRING function.
Posted
Updated 6-Sep-17 9:49am

SQL 2016 introduced a STRING_SPLIT function which should do the job:

STRING_SPLIT (Transact-SQL) | Microsoft Docs[^]
 
Share this answer
 
v2
If you need to treat a name as separate parts, then get them entered as separate parts and store them separately - you can't assume that a user will have just two names( or even more than one!), or that the one to the left of a space is the "first name" - it can be the family name.

In this case, that's almost certainly what is causing your error: if someone in your database only has one name then that is exactly the error you will get, becuase if there is no match, CHARINDEX will return zero ...
 
Share this answer
 
You get the specific message you're getting when you don't specify the size of the variable NVARCHAR so THAT defaults to 1. And the LENGTH is, after all your math, therefore zero.

Here's what shows my drift.
DECLARE @exampleY as nvarchar(20)
SET @exampleY = 'Nater Termi'	

SELECT LEFT(@exampleY,CHARINDEX(' ',@exampleY)-1) AS [pisanCP01]-- 'Nater'
SELECT RIGHT(@exampleY,CHARINDEX(' ',@exampleY)-1) AS [pisanCP0A]-- 'Termi'

IF you did this:
DECLARE @exampleZ as nvarchar
SET @exampleZ = 'Scobie Agent'

Then tried to get the length of the string you're inputting, you'd get this:
SELECT LEN(@exampleZ)
/*
     1
*/

Instead of '12'
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900