Solved

Substring error using charindex

Posted on 2015-01-30
4
81 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 45

Expert Comment

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

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.

Join & Write a Comment

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
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…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

708 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

12 Experts available now in Live!

Get 1:1 Help Now