Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

SQL Return first four values from delimited string

Posted on 2016-07-22
2
Medium Priority
?
36 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:Mauro Cazabonnet
2 Comments
 
LVL 70

Accepted Solution

by:
Éric Moreau earned 2000 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:Mauro Cazabonnet
ID: 41724978
Awesome thx!!!!!!
Set up as a UDF....
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
One of the most important things in an application is the query performance. This article intends to give you good tips to improve the performance of your queries.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

926 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