SQL Syntax to pull part of String Field back..? (CharIndex..?)

Posted on 2013-05-23
Last Modified: 2013-05-29
My data field looks like this:

"Adventist Health System - Winter Park, FL"

This is a single String/Text Field and is consistent with the " - " and the ", " between the HospitalName and CityName, and the CityName and StateCode. All entries in this field follow this same format:  HospitalName " - " CityName ", " StateCode

I have a requirement to pull ONLY the CITYNAME from the above string field.

So that would be I need to pull the TEXT between the " - " and the ", " 

I need the function and syntax to use....THANKS
Question by:MIKE
LVL 23

Expert Comment

ID: 39191897
You want PATINDEX and SUBSTRING.  I broke this down into more steps than necessary, just so you can understand it better.

DECLARE @str VARCHAR(100) = 'Adventist Health System - Winter Park, FL';

DECLARE @sep1loc INT = PATINDEX('% - %', @str) + 3;
DECLARE @sep2loc INT = PATINDEX('%, %', @str);
DECLARE @citystrlen INT = @sep2loc - @sep1loc;
SELECT @sep1loc, @sep2loc, DATALENGTH(@str), @citystrlen
SELECT SUBSTRING(@str, @sep1loc, @citystrlen);

Open in new window

LVL 16

Expert Comment

by:Surendra Nath
ID: 39191899
the below one should help
declare @t varchar(200) 
set @t = 'Adventist Health System - Winter Park, FL'
select substring(@t,charindex('-',@t)+1,charindex(',',@t)-charindex('-',@t)-1)

Open in new window

LVL 23

Expert Comment

ID: 39191913
Did you want this in a function?  Easy enough.

USE tempdb

CREATE FUNCTION dbo.city_from_hospital_name
(@instr VARCHAR(1000))
	DECLARE @sep1loc INT = PATINDEX('% - %', @instr) + 3;
	DECLARE @sep2loc INT = PATINDEX('%, %', @instr);
	DECLARE @citystrlen INT = @sep2loc - @sep1loc;
	-- SELECT @sep1loc, @sep2loc, DATALENGTH(@str), @citystrlen
	RETURN SUBSTRING(@instr, @sep1loc, @citystrlen);

DECLARE @str VARCHAR(100) = 'Adventist Health System - Winter Park, FL';
SELECT dbo.city_from_hospital_name(@str);

Open in new window

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)


Expert Comment

ID: 39191998
If you don't want to you variables or functions here is a straight SQL example depending on the data you may have to play with the string manipulation.  

select 'Adventist Health System - Winter Park, FL' [Hospital],
      charindex('-','Adventist Health System - Winter Park, FL') [DashStartPosition],
      charindex(', ','Adventist Health System - Winter Park, FL') [StateStartPosition],
      ltrim(substring('Adventist Health System - Winter Park, FL',charindex('-','Adventist Health System - Winter Park, FL') +1,(charindex(', ','Adventist Health System - Winter Park, FL')-1) - (charindex('-','Adventist Health System - Winter Park, FL')))) [CityName]
LVL 32

Expert Comment

ID: 39192060
select substring(datafield,charindex('-',datafield) + 2,charindex(',',datafield) - charindex('-',datafield) - 2)
from yourtable;
LVL 69

Accepted Solution

ScottPletcher earned 500 total points
ID: 39192833
A CROSS APPLY makes the code so much easier to read, follow and maintain; and often prevents having to repeat CHARINDEXes and other functions:

    LEFT(city_and_state, CHARINDEX(',', city_and_state) - 1) AS city
    SELECT 'Adventist Health System - Winter Park, FL' AS string UNION ALL
    SELECT 'Baptist Hospital - Pensacola, FL'
) AS test_data
    --strip the orig 'name - city, st' string in the table to just 'city, st'
    SELECT SUBSTRING(string, CHARINDEX('-', string) + 2, 200) AS city_and_state
) AS ca1

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
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
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

932 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

11 Experts available now in Live!

Get 1:1 Help Now