Solved

Substring error using charindex

Posted on 2015-01-30
4
93 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 50

Expert Comment

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

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

Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

Question has a verified solution.

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

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…
In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.

729 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