Solved

SQL Return first four values from delimited string

Posted on 2016-07-22
2
28 Views
Last Modified: 2016-07-22
I'm a bit stuck
trying to return the first four values of string of varying length
Substrings is not consistent and parsename has a 4 limitiation

Sample
US-HVD-PROD-PNO-01-VM
EMEA-HVD-PROD-WGC-01-VM
APAC-HVD-UAT-PNO-02-VM

Need to return

US-HVD-PROD-PNO
EMEA-HVD-PROD-WGC
APAC-HVD-UAT-PNO

Any help much appreciated
0
Comment
Question by:mcazabonnet
2 Comments
 
LVL 69

Accepted Solution

by:
Éric Moreau earned 500 total points
ID: 41724857
wouldn't it be something like this:
DECLARE @value VARCHAR(100) = 'US-HVD-PROD-PNO-01-VM' -- EMEA-HVD-PROD-WGC-01-VM    APAC-HVD-UAT-PNO-02-VM
DECLARE @count INT = 0
DECLARE @start INT = 0

WHILE @count < 4
BEGIN
	SELECT @start, @count
	SET @start = CHARINDEX('-', @value, @start+1)
	IF @start = 0 
		BREAK
	ELSE
		SET @count = @count + 1
END

SELECT @start, SUBSTRING(@value, 0, @start)

Open in new window


you could easily create a UDF from it.
0
 
LVL 4

Author Closing Comment

by:mcazabonnet
ID: 41724978
Awesome thx!!!!!!
Set up as a UDF....
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

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.
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

705 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