Question

SQL, selecting with a multi value field.

Asked by: mattososky

I have some table data I want to select from. The problem is that one of the fields is a pipe delimeted set of values. I want to return a dataset that treats each on of those values as a unique field. Data looks somthing like this:

Field 1             Field 2
Matt                 QQ|XX|YY
Bob                  AA|XX

I want the sql to return

Field 1             Field 2
Matt                 QQ
Matt                 XX
Matt                 YY
Bob                  AA
Bob                  QQ

How to approach this problem?
Thanks.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-02-04 at 13:03:07ID24113595
Tags

SQL

Topics

SQL Query Syntax

,

MS SQL Server

,

Databases Miscellaneous

Participating Experts
4
Points
500
Comments
15

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. dd/mm/yy
    hi, in default MS-SQL store the datetime in mm/dd/yy format, how to change to format to be dd/mm/yy?
  2. what is the use of qw and qq in perl
    Hi, Can anyone help me in knowing the use of qw and qq and their difference. I would appreciate if you provide me with examples. Thanks
  3. Multi Table SQL Query in one Dataset
    Is it possible to store the data from a multi table sql statment in one dataset.
  4. Multi-DB queries in datasets
    I'm using datasets almost exclusively for SQL Express IO to keep my programming as simple as possible (newbie stretch situation). However, I've run into a situation where it would be nice to have a query that pulls from multiple databases. I'm thinking I can't do that using...
  5. Oracle - Parsing Delimeted String
    Can anyone share or point to a pl/sql function that will single quote fields within a comma delimeted string to be used later in an IN statement. thanks

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ScottPletcherPosted on 2009-02-04 at 13:08:43ID: 23553525

SELECT field1, RTRIM(LTRIM(SUBSTRING(';' + field2 + ';', seqNum + 1,
            CHARINDEX(';', ';' + field2 + ';', seqNum + 1) - seqNum - 1))) AS value
FROM tablename
INNER JOIN seqNums ON
    seqNum BETWEEN 1 AND LEN(';' + field2 + ';') - 1
    AND SUBSTRING(';' + field2 + ';', seqNum, 1) = ';'
ORDER BY field1

 

by: ScottPletcherPosted on 2009-02-04 at 13:09:41ID: 23553536

Best way is to create a sequential numbers table and use that to do the split, as I just posted.  Below is the code for creating the seqNums table (also called a "tally" or "numbers" table).

DECLARE @maxValueToGenerate INT
 
-- chg next value to the highest value you need; 
-- the current code supports up to 100M - 1, but you could increase that if you wanted to
 
SET @maxValueToGenerate = 16000
 
IF OBJECT_ID('seqNums') IS NOT NULL
    DROP TABLE seqNums
 
CREATE TABLE seqNums (
    seqNum INT,
    CONSTRAINT seqNums_CI --don't remove, improves performance!
        UNIQUE CLUSTERED (seqNum) WITH FILLFACTOR = 100
    )
 
INSERT INTO seqNums
SELECT [1s] + [10s] + [100s] + [1000s] + [10Ks] + [100Ks] + 
	[1Ms] + [10Ms] /*+ [100Ms]*/
FROM (
    SELECT 0 AS [1s] UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL 
    SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL 
    SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
) AS digits
CROSS JOIN (
    SELECT 00 AS [10s] UNION ALL SELECT 10 UNION ALL SELECT 20 UNION ALL 
    SELECT 30 UNION ALL SELECT 40 UNION ALL SELECT 50 UNION ALL SELECT 60 UNION ALL 
    SELECT 70 UNION ALL SELECT 80 UNION ALL SELECT 90
) AS [10s]
CROSS JOIN (
	SELECT [100s]
	FROM (
    SELECT 000 AS [100s] UNION ALL SELECT 100 UNION ALL SELECT 200 UNION ALL 
    SELECT 300 UNION ALL SELECT 400 UNION ALL SELECT 500 UNION ALL SELECT 600 UNION ALL 
    SELECT 700 UNION ALL SELECT 800 UNION ALL SELECT 900
	) inlineData
	WHERE [100s] <= @maxValueToGenerate
) AS [100s]
CROSS JOIN (
	SELECT [1000s]
	FROM (
    SELECT 0000 AS [1000s] UNION ALL SELECT 1000 UNION ALL SELECT 2000 UNION ALL 
    SELECT 3000 UNION ALL SELECT 4000 UNION ALL SELECT 5000 UNION ALL SELECT 6000 UNION ALL 
    SELECT 7000 UNION ALL SELECT 8000 UNION ALL SELECT 9000
	) inlineData
	WHERE [1000s] <= @maxValueToGenerate
) AS [1000s]
CROSS JOIN (
	SELECT [10Ks]
	FROM (
    SELECT 00000 AS [10Ks] UNION ALL SELECT 10000 UNION ALL SELECT 20000 UNION ALL 
    SELECT 30000 UNION ALL SELECT 40000 UNION ALL SELECT 50000 UNION ALL SELECT 60000 UNION ALL 
    SELECT 70000 UNION ALL SELECT 80000 UNION ALL SELECT 90000
	) inlineData
	WHERE [10Ks] <= @maxValueToGenerate
) AS [10Ks]
CROSS JOIN (
	SELECT [100Ks]
	FROM (
    SELECT 000000 AS [100Ks] UNION ALL SELECT 100000 UNION ALL SELECT 200000 UNION ALL 
    SELECT 300000 UNION ALL SELECT 400000 UNION ALL SELECT 500000 UNION ALL SELECT 600000 UNION ALL 
    SELECT 700000 UNION ALL SELECT 800000 UNION ALL SELECT 900000
	) inlineData
	WHERE [100Ks] <= @maxValueToGenerate
) AS [100Ks]
CROSS JOIN (
	SELECT [1Ms]
	FROM (
    SELECT 0000000 AS [1Ms] UNION ALL SELECT 1000000 UNION ALL SELECT 2000000 UNION ALL 
    SELECT 3000000 UNION ALL SELECT 4000000 UNION ALL SELECT 5000000 UNION ALL SELECT 6000000 UNION ALL 
    SELECT 7000000 UNION ALL SELECT 8000000 UNION ALL SELECT 9000000
	) inlineData
	WHERE [1Ms] <= @maxValueToGenerate
) AS [1Ms]
CROSS JOIN (
	SELECT [10Ms]
	FROM (
    SELECT 00000000 AS [10Ms] UNION ALL SELECT 10000000 UNION ALL SELECT 20000000 UNION ALL 
    SELECT 30000000 UNION ALL SELECT 40000000 UNION ALL SELECT 50000000 UNION ALL SELECT 60000000 UNION ALL 
    SELECT 70000000 UNION ALL SELECT 80000000 UNION ALL SELECT 90000000
	) inlineData
	WHERE [10Ms] <= @maxValueToGenerate
) AS [10Ms]
/*
CROSS JOIN (
	SELECT [100Ms]
	FROM (
    SELECT 000000000 AS [100Ms] UNION ALL SELECT 100000000 UNION ALL SELECT 200000000 UNION ALL 
    SELECT 300000000 UNION ALL SELECT 400000000 UNION ALL SELECT 500000000 UNION ALL SELECT 600000000 UNION ALL 
    SELECT 700000000 UNION ALL SELECT 800000000 UNION ALL SELECT 900000000
	) inlineData
	WHERE [100Ms] <= @maxValueToGenerate
) AS [100Ms]
*/
WHERE [1s] + [10s] + [100s] + [1000s] + [10Ks] + [100Ks] + [1Ms] + [10Ms] /*+ [100Ms]*/ <= @maxValueToGenerate
ORDER BY [1s] + [10s] + [100s] + [1000s] + [10Ks] + [100Ks] + [1Ms] + [10Ms] /*+ [100Ms]*/
 
DBCC SHOWCONTIG(seqNums) --make sure table is highly contig for max performance
 
SELECT COUNT(*) FROM seqNums WITH (NOLOCK) --verify that the expected number of rows were generated
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:

Select allOpen in new window

 

by: matthewspatrickPosted on 2009-02-04 at 13:09:44ID: 23553537

mattososky said:
>>How to approach this problem?

Modify the design to either use 3 columns instead of one, or probably even better, shunt those values off to
another table in a one-to-many relationship.  That's the best way to approach the problem.

Patrick

 

by: imitchiePosted on 2009-02-04 at 13:29:13ID: 23553749

Try this cleaner solution

drop table q24113595
GO
create table q24113595 (field1 varchar(10), field2 varchar(max))
GO
insert into q24113595
select 'Matt', 'QQ|XX|YY' union all
select 'Bob', 'AA|XX'
GO
 
WITH CTE (Field1, Field2, Remain, Level)
AS
(
-- Anchor member definition
	SELECT Field1, Field2 = Field2, Remain = Field2, Level = 0
	FROM q24113595
	UNION ALL
-- Recursive member definition
	SELECT Field1,
		Field2 = left(Remain, isnull(position_of_space, remain_length) -1),
		Remain = right(Remain, isnull(remain_length - position_of_space, 0)),
		Level = 1
	FROM
	(
	SELECT
		position_of_space = nullif(PatIndex('%|%', Remain), 0),
		remain_length = len(Remain),
		CTE.Field1, CTE.Remain
	FROM CTE
	INNER JOIN q24113595 on q24113595.Field1 = CTE.Field1
	WHERE Remain <> ''
	) X
)
-- Statement that executes the CTE
SELECT Field1, Field2
FROM CTE
WHERE Level = 1
GO
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:

Select allOpen in new window

 

by: ScottPletcherPosted on 2009-02-04 at 13:40:34ID: 23553888

I'm not so sure that's really cleaner.  The execution plans show Table Spool -- meaning tempdb -- being used ... and that was for just two rows.

 

by: imitchiePosted on 2009-02-04 at 13:45:04ID: 23553942

Scott,
Thank you for your unsolicited comment.
I assure you I know what I am doing.

I will let the man form his own opinion.

 

by: mattososkyPosted on 2009-02-04 at 13:46:14ID: 23553957

It is not an option to modify the source data. That's why I'm modifying the dataset right here.

Also, it is not possible to use other tables, as I am working within an application, and I'm limited to sql selects to return the data I need. Also, Scott, didn't know if it was ment to be ;'s in your code. I specified the multi value field was deliminated with pipes ( | ).

 

by: imitchiePosted on 2009-02-04 at 13:57:07ID: 23554093

mattososky, no table is being created.
q24113595 is the only table involved there.

I created q24113595 as a mirror to your table.
The portion from WITH CTE .... onwards is SQL Syntax.
CTE is a virtual table.
Never mind.
Check "CTE" in SQL books online, if you can understand it or just try to use my example code, you'll see it work. Otherwise, it's going to go over your head, as it has Scott's.

 

by: mattososkyPosted on 2009-02-04 at 14:08:14ID: 23554235

Using the vitual table is also not an option as I am not using SQL Server. I am using a customized application that accesses flat files with the HXTT driver. Transforms sql statements to data searches on flat files. Most standard sql snytax is supported. The CTE is not.

 

by: imitchiePosted on 2009-02-04 at 14:17:14ID: 23554335

Hi mattososky,
Thank you for the clarification.
I missed the part where it says you were using a customized application.
From what I am hearing, creating a view/function with the CTE should work?

CREATE VIEW v24113595
AS
WITH CTE (Field1, Field2, Remain, Level)
AS
(
-- Anchor member definition
        SELECT Field1, Field2 = Field2, Remain = Field2, Level = 0
        FROM q24113595
        UNION ALL
-- Recursive member definition
        SELECT Field1,
                Field2 = left(Remain, isnull(position_of_space, remain_length) -1),
                Remain = right(Remain, isnull(remain_length - position_of_space, 0)),
                Level = 1
        FROM
        (
        SELECT
                position_of_space = nullif(PatIndex('%|%', Remain), 0),
                remain_length = len(Remain),
                CTE.Field1, CTE.Remain
        FROM CTE
        INNER JOIN q24113595 on q24113595.Field1 = CTE.Field1
        WHERE Remain <> ''
        ) X
)
-- Statement that executes the CTE
SELECT Field1, Field2
FROM CTE
WHERE Level = 1
GO
 
--
 
SELECT * FROM v24113595
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:

Select allOpen in new window

 

by: Sharath_123Posted on 2009-02-04 at 14:24:43ID: 23554406

Is it possible to create function in your application? If yes, i can give you a function for this.

 

by: ScottPletcherPosted on 2009-02-04 at 14:34:43ID: 23554518

I'm not using a virtual table, both of my table are physical tables.

But they do require that you be able to join a physical table with your input.

 

by: mattososkyPosted on 2009-02-05 at 07:38:15ID: 23560318

Sorry, not sure these are options with the interface I have.
-I can not use the CTE
-I can not create my own functions.
-I can not create another table in the dabase

I was hoping that I could do something along the lines on a string split in a sub query, then use that as a selection source in the main select. Sounds like there is nothing so easy.

 

by: ScottPletcherPosted on 2009-02-05 at 08:23:09ID: 23560901

In the future, it would be helpful if you would state those types of restrictions in your original q.

We are trying to provide an optimum solution, so we will consider every option, and we are just wasting our time if you can't use them anyway.

Given all the restrictions you have, I don't know of a good way to solve your problem, esp. if the number of values in the row can exceed 3.

 

by: ScottPletcherPosted on 2009-02-05 at 08:25:34ID: 23560924

>> Scott,
Thank you for your unsolicited comment.
I assure you I know what I am doing.
I will let the man form his own opinion. <<

I did not comment on you personally, but on the plan that SQL actually created to execute your query.  That plan is not an opinion, it is a fact.

If you can show that SQL can/will generate a different with the right "tweaking" of code or "hints", then that would be a useful response.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...