Solved

parse a string separated by hyphens

Posted on 1998-10-22
2
510 Views
Last Modified: 2008-07-03
I have a field that has an unknown number of numbers separated by hyphens.  I need to select each of the numbers and insert them into their own field.  How can I do this with sql?
Thank you!
0
Comment
Question by:may11998
2 Comments
 
LVL 7

Accepted Solution

by:
spiridonov earned 50 total points
ID: 1090758
You can't do it with one sql statement, you should use stored procedure with cursor to perform this operation. Soemthing like (for 3 values ):

CREATE PROCEDURE TEST
as
DECLARE @combo_field varchar(255)
DECLARE @v1 VARCHAR(255)
DECLARE @v2 VARCHAR(255)
DECLARE @v3 VARCHAR(255)

DECLARE c CURSOR FOR
SELECT  combo_field
FROM t
OPEN c
FETCH NEXT FROM c  into @combo_field
WHILE @@fetch_status<>-1
BEGIN
IF @@fetch_statua<>-2
BEGIN
SELECT @v1=SUBSTRING(@combo_field,1,CHARINDEX(";",@combo_field)-1)
SELECT @combo_field=SUBSTIRNG(@combo_field,CHARINDEX(";",@combo_field)+1,DATALENGTH(@combo_field)-DATALENGTH(@v1)-1)
SELECT @v2=SUBSTRING(@combo_field,1,CHARINDEX(";",@combo_field)-1)
SELECT @combo_field=SUBSTIRNG(@combo_field,CHARINDEX(";",@combo_field)+1,DATALENGTH(@combo_field)-DATALENGTH(@v2)-1)
SELECT @v3=@combo_field
UPDATE t
SET v1=@v1,v2=@v2,v3=@v3
WHERE combo_field=@combo_field
end
FETCH NEXT FROM c  into @combo_field
end


0
 

Author Comment

by:may11998
ID: 1090759
Thanks!
0

Featured Post

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Join & Write a Comment

Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
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…
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.

758 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

20 Experts available now in Live!

Get 1:1 Help Now