Solved

Substring error using charindex

Posted on 2015-01-30
4
83 Views
Last Modified: 2015-01-30
Here is a string extraction statement that should work but does not:

substring(Name,1,CHARINDEX(',', Name)-1) AS GuarLname

The data looks similar to this:

SMITH,JOHN

I am getting an Invalid Length Parameter error.

What would be the correct syntax?

Thanks

Glen
0
Comment
Question by:GPSPOW
  • 2
4 Comments
 
LVL 25

Expert Comment

by:Lee Savidge
ID: 40579996
This works

declare @name nvarchar(100)
select @name = 'smith,john'
select substring(@name,1,CHARINDEX(',', @name)-1) AS GuarLname

Open in new window


You may have nulls in your selection?

Put a where clause in to filter out nulls and values that don't have a comma in.
0
 
LVL 46

Expert Comment

by:Vitor Montalvão
ID: 40580001
You'll get that error if a record doesn't have the comma.
0
 
LVL 46

Accepted Solution

by:
Vitor Montalvão earned 500 total points
ID: 40580020
Try this solution:
SELECT substring(Name,1,CASE CHARINDEX(',', Name)
          WHEN 0 THEN LEN(Name)
	  ELSE CHARINDEX(',', Name)-1
    END)  AS GuarLname
FROM YourTableName

Open in new window

0
 

Author Closing Comment

by:GPSPOW
ID: 40580029
Thank you.

You were correct.

I did a query and found 22 records out of 500,000 with no commas in the name.

Glen
0

Featured Post

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now