Splitting out string, using the results to lookup reference, then returning the reference name as a string?

I have a field that contains a comma separated string of sys_id’s that relate to another table.
I am trying to write a query that returns the name value from the reference table, so that the result is a comma separated string of the name field.
Can anyone help with the SQL required to split out the sys_id’s, do the look-up and return the names back into a string?
Table1
Number
Category
1001
Sys_id1, Sys_id3, Sys_id9
1002
Sys_id3
1003
Sys_id4,Sys_3
1004
Sys_id1, Sys_id9, Sys_id10, Sys_id6
Category Reference Table
Category Sys_id
Category_Name
Sys_id1
Consulting
Sys_id3
Negotiate
Sys_id4
Planning
Sys_id6
Building
Sys_id9
Receipt
Sys_id10
Complete
The result I am looking for would be.
Number
Category
1001
Consulting, Negotiate, Receipt
1002
Negotiate
1003
Planning, Negotiate
1004
Consulting, Receipt, Complete, Building

I am not going to arguee regarding your model, but you should consider normalizing it.
The idea is to have a function to split the string and return a row for each element in the list. Dump the result into a table and then use FOR XML PATH to do the string aggregation.
To learn about different methods you could use to create the split function refer to this article.
Arrays and Lists in SQL Server
http://www.sommarskog.se/arrays-in-sql.html
Here is an example using XML methods. This is just an example and it doesn't deal with proper indexing, weird characters as part of the list that can't be translated as xml, etc.
SET NOCOUNT ON;
USE tempdb;
GO
DECLARE @T TABLE (
Number int,
Category varchar(50)
INSERT INTO @T (Number, Category)
VALUES
(1001, 'Sys_id1, Sys_id3, Sys_id9'),
(1002, 'Sys_id3'),
(1003, 'Sys_id4, Sys_id3'),
(1004, 'Sys_id1, Sys_id9, Sys_id10, Sys_id6');
DECLARE @R TABLE (
Sys_id varchar(15),
Category_Name varchar(35)
INSERT INTO @R (Sys_id, Category_Name)
VALUES
('Sys_id1', 'Consulting'),
('Sys_id3', 'Negotiate'),
('Sys_id4', 'Planning'),
('Sys_id6', 'Building'),
('Sys_id9', 'Receipt'),
('Sys_id10', ' Complete');
DECLARE @W TABLE (
Number int,
pos int,
Sys_id varchar(15),
PRIMARY KEY (Number, Sys_id)
INSERT INTO @W (Number, pos, Sys_id)
SELECT
A.Number,
ROW_NUMBER() OVER(PARTITION BY A.Number ORDER BY N.x) AS pos,
N.x.value('(text())[1]', 'varchar(15)') AS Sys_id
FROM
@T AS A
CROSS APPLY
(SELECT A.Category AS [text()] FOR XML PATH('')) AS B(c)
CROSS APPLY
(SELECT CAST('<l>' + REPLACE(B.c, ', ', '</l><l>') + '</l>' AS xml)) AS C(x)
CROSS APPLY
C.x.nodes('/l') AS N(x);
SELECT
A.Number,
STUFF(
SELECT
', ' + C.Category_Name
FROM
@W AS B
INNER JOIN
@R AS C
ON C.Sys_id = B.Sys_id
WHERE
B.Number = A.Number
ORDER BY
B.pos
FOR XML PATH(''), TYPE
).value('(text())[1]', 'varchar(MAX)'), 1, 2, '') AS Category
FROM
@T AS A;
GO
AMB
Some guidelines for posting questions...

Similar Messages

  • I can't send out email using my iPhone4. I tried to follow the step provided to solve but still not working. What should I do?

    I can't send out email using my iPhone4. I tried to follow the step provided to solve but still not working. What should I do?

    Contact your mail provider and get the CORRECT settings for the outgoing server to set up on your phone.

  • One question of the method have two chance to return the result.

    Hello All,
    I get a problem at present.The code is following.
    package com.ricky.test;
    public class Test {
         public static void main(String args[]) {
              System.out.println(kkk());
         public static int kkk() {
              int k = 0;
              try {
                   k += 2;
                   return k;
              } catch (Exception e) {
                   k++;
                   return k;
              } finally {
                   k += 5;
                   System.out.println("get Here");
                   return k;
    }why does the result is 7.Isn't it return at the "try" part? and my eclipse alarm that "finally block doesn't complete normally";
    thank you for your help!(I hope someone know my mean,because i'm not good at english. )

    if I change the method to :
    public static int kkk() {
              int k = 0;
              try {
                   k += 2;
                   return k;
              } catch (Exception e) {
                   k++;
                   return k;
              } finally {
                   k += 5;
         }the result is 2(just execute k += 2 and then return the result.)
    but if i change the method to
    public static StringBuffer kkk1() {
              StringBuffer result = new StringBuffer("1");
              try {
                   result = result.append("2");
                   return result;
              } catch (Exception e) {
                   result = result.append("3");
                   return result;
              } finally {
                   result = result.append("4");
                   // return result;
         }the result is 124(the finally block effect the result value)Why?
    Maybe is the result is the memory address.is that right?

  • The result of a direct action returned NULL/nil.

    I'm new to Macs so please bear with me. I've been tasked with setting up a new iMac (20 inch display - totally stock - bought on Saturday.) After plugging it in and started running through the registration, setting up the wireless access then it looked like the setup was doing something with the camera suddenly it flashed to the following message:
    "the result of a direct action returned NULL/nil." the Continue and Back buttons at the bottom of the page were dimmed out. The only thing I could do was reboot the computer.
    Is there any way to restart the "setup sequence" - as if I just plugged it in and turned it on for the first time? Have I missed anything in the setup because of this error? Anyone know why this happened? I've tried to search on this topic but couldn't find anything. If I've missed something please direct me to the appropriate link.
    Thanks.
    20 inch iMac 2.16GHz Intel Core 2 Duo   Mac OS X (10.4.6)  

    Go to ~user/Library/Assistants and double click the file Send Registration.setup and it should relaunch the Mac OS X Setup Assistant.

  • HT1338 When I email an attachment with "Always Sent Windows-Friendly Attachments" checked, the result is a picture embedded in the body of the email, not a attachment.  What am I doing wrong.

    When I email an attachment (a .jpg file) with "Always Send Windows-Friendly Attachments" checked, the result is a picture embedded in the body of the email, not a attachment.  What am I doing wrong.

    1. "Always Send Windows-Friendly Attachments" has nothing to do with the display of attachments on either your machine or other ones. It's an esoteric setting that strips the resource fork from Mac files (that might have them) which could apper as a duplicate file on the Windows machine.
    2. Send Plain Text emails. Then it will always be received as an attachment.

  • How do i keep the results from a formula but delete the original data

    I want to delete the column of original data and only keep the results.

    Hi rdavidland,
    Select and copy the cells that contain the formula.
    Menu > Edit > Paste Formula Results.
    Delete the original data.
    Regards,
    Ian.

  • You cannot use this product at this time. You must repair the problem by uninstalling and then reinstalling the product or contacting your IT administrator or adobe customer support for help....here I am

    You cannot use this product at this time. You must repair the problem by uninstalling and then reinstalling the product or contacting your IT administrator or adobe customer support for help

    This forum is none of those things.  That being said, we may be able to help.
    Have you tried uninstalling and reinstalling the product?  If not, please consider following these instructions:
    Use the CC Cleaner Tool to solve installation problems | CC, CS3-CS6
    -Noel

  • How do I turn off open apps? You use to be able to press the home button twice and then hold the app icon until is vibrated and then turn it off.

    How do I turn off open apps? You use to be able to press the home button twice and then hold the app icon until is vibrated and then turn it off.

    WOW - Can't this be a flashing message in the forums since it's been asked about a 1,000 times now.

  • Just bought a new iphone4 and was loading os6 and now it won't turn on. the apple glows like it is starting up, then the screen goes black and then repeats the same process over and over. i have tried to reboot multiple times now

    just bought a new iphone4 and was loading os6 and now it won't turn on. the apple glows like it is starting up, then the screen goes black and then repeats the same process over and over. i have tried to reboot multiple times now

    I am assuming the phone was working prior to you installing IOS 6? Did you use itunes to install IOS 6 or just run from the phone?
    When I tried to do the Over The Air update to IOS6 on my iPhone 4, it errored out and I had to connect it to iTunes and select "Restore" from the summary screen after iTunes finds the phone is connected. If this works for you, it will go through a couple of reboots that take a few minutes to complete. It should then give you the option to start with a fresh new phone or to use one of your previous backups to load your contacts and other information, provided you have backed up the phone previously.
    I hope this helps you my friend!

  • Hello. I have downloaded ps cc in the Norwegian version. I then deleted the Norwegian Verson and will re installPerfect ps cc english verson. When I try to download ps cc again I do not get pressure on ps cc in creative clode distributions appear as updat

    I have downloaded ps cc in the Norwegian version. I then deleted the Norwegian Verson and will re installPerfect ps cc english verson. When I try to download ps cc again I do not get pressure on ps cc in creative clode distributions appear as updated What can I installation alert ps cc again ?

    That is not a practically empty xinitrc - that file only needs one line: exec WM.  Other things are entirely optional, and some of them very useful, but I'd encourage you to stick with the simplest xinitrc that will do what you require.
    Is slim involved?  Probably.  That is the source of many problems.  But to start narrowing this down, I have 3 suggestions:
    1) temporarily (at least) change your inittab to default to runlevel 3 ... actually, is it currently set to 5 or 3? if it is currently 3 that would explain why slim doesn't start.
    2) at a tty in runlevel 3 use "xinit" instead of "startx".  Startx is fine most of the time, but it is essentially just a complex wrapper for xinit.  That complexity can often iadd useful functionality, but it *always* makes troubleshooting more difficult.  So for now just use a vanilla 'xinit'.
    3) remove dbus-launch from your exec line in xinitrc.  This is done by console-kit so it is redundant and potentially problematic.  Further BOTH of these are taken care of by slim, so I'd even suggest getting both a jump start on being ready for slim and simplifying troubleshooting by removing both of them.  Just make that line "exec openbox-session"
    Edit: adding one more:
    4) temporarily switch out openbox-session for openbox.  I suspect the reason feh's setting of the background is getting overridden is due to a script or setting in openbox's autostart settings - many of these are only invoked when "openbox-session" is called, while "openbox" starts *just* the window manager itself.
    Last edited by Trilby (2012-10-03 17:30:36)

  • When I turn on my iMac it comes up with the icon which I then log into. The password works and I then get the apple icon and the spinning wheel. After a minute it turns into a prohibited icon. If I log on the guest icon I get to Safari. Help!

    When I turn on my iMac it comes up with the login icons which I then choose and log into. The password works and I then get the apple icon and the spinning wheel. After about a minute the Apple icon turns into a prohibited icon. However, if I log in under the guest icon, I can access the wifi and get to Safari. I really don't know what to do next. Any help would be gratefully appreciated.

    Are you running any A-V? If it's an iMac 21.5, I don't think you're running Leopard, 10.5. Probably at least Snow Leopard, 10.6. This is the Leopard forum.
    This article says meant for 10.3.9 and eariler, but contains some still useful suggestions.
    http://support.apple.com/kb/TS1411
    Try a Safe Boot. Shift at the startup chime and expect a much longer time to boot. This will bring you to a login screen with "Safe Boot" in red.
    Look at this as well.
    http://support.apple.com/kb/TS1417

  • I had a repair done on my MacBook Pro and had to have a new hard drive installed. The Apple Auth Repair Shop then updated the OS from 10.6.8 to 10.7.5. Now my iPhoto v 9.2.3 will not open and it sounds like it will not work with this OS. Can you plea

    I had a repair done on my MacBook Pro and had to have a new hard drive installed. The Apple Auth Repair Shop then updated the OS from 10.6.8 to 10.7.5. Now my iPhoto v 9.2.3 will not open and it sounds like it will not work with this OS. Can you please advise?

    You may need many other updates to retain compatibility with Lion. I suggest you reinstall Snow Leopard. Unfortunately, you will need to erase the drive first. Be sure to backup your data if you haven't done so already.
    Clean Install of Snow Leopard
    Be sure to make a backup first because the following procedure will erase
    the drive and everything on it.
         1. Boot the computer using the Snow Leopard Installer Disc or the Disc 1 that came
             with your computer.  Insert the disc into the optical drive and restart the computer.
             After the chime press and hold down the  "C" key.  Release the key when you see
             a small spinning gear appear below the dark gray Apple logo.
         2. After the installer loads select your language and click on the Continue
             button. When the menu bar appears select Disk Utility from the Utilities menu.
             After DU loads select the hard drive entry from the left side list (mfgr.'s ID and drive
             size.)  Click on the Partition tab in the DU main window.  Set the number of
             partitions to one (1) from the Partitions drop down menu, click on Options button
             and select GUID, click on OK, then set the format type to MacOS Extended
             (Journaled, if supported), then click on the Apply button.
         3. When the formatting has completed quit DU and return to the installer.  Proceed
             with the OS X installation and follow the directions included with the installer.
         4. When the installation has completed your computer will Restart into the Setup
             Assistant. After you finish Setup Assistant will complete the installation after which
             you will be running a fresh install of OS X.  You can now begin the update process
             by opening Software Update and installing all recommended updates to bring your
             installation current.
    Download and install Mac OS X 10.6.8 Update Combo v1.1.

  • That logic not to pay the money To customer once he returned the stock

    Dear SD Experts
    I Dont want to disturb This link Flow, so that is the reason i am asking my doubt here
    Return Sales order - update of Item category change
    I Am very interestingly to know what is That logic not to pay the money To customer once he returned the stock , then changing The item category in returns ....Please  explain

    Venu,
    Is the return authorized by the company?  If yes, what are the terms of return. If the company has a explicit policy like:  "Only replacement, but no credit", your logic can stand.  The reason could be that the item once opened, cannot be or should not be reused.  Like onetime-use plastic molds. Once molded, it has no value. Or opened onetime-use sanitized surgical instruments. 
    Another scenario I can think of is that it is a custom made goods.  For example, you want a chopping board with your name engraved on it, Before delivery, the maker takes an approval from you after showing the design work.  You approve the design, and give a go ahead. In such a scenario, the product is of no use to the seller.
    Any any of the case, like Moazza said the policy should be very explicit.
    Thanks

  • Recompile all the GMD libraries and forms, then retest the issue.

    Hi
    One of our consultant working in Oracle Process Manufacturing, getting the following error.
    ORA-04062: signature of package "APPS.GMD_FORMULA_DETAIL_PVT" has been changed.
    Then according to Metalink Doc id: 374204.1, the solution is as follows:
    Recompile all the GMD libraries and forms, then retest the issue
    Can anybody suggest me how to recompile these libraries & forms? Is it using adadmin (Compile/Reload Database Entities Tasks) menu or not? Need help.
    Thanks

    Run adadmin and select:
    1. Generate Applications Files menu
    2. Generate form files
    Do you want to regenerate Oracle Forms PL/SQL library files [Yes] ?
    Do you want to regenerate Oracle Forms menu files [Yes] ?
    Do you want to regenerate Oracle Forms executable files [Yes] ?
    Enter list of products ('all' for all products) [all] : gmd
    Generate specific forms objects for each selected product [No] ?

  • My CS2 Illustrator goes through all the motions to open but then at the end, nothing happens. It has

    My CS2 Illustrator goes through all the motions to open but then at the end, nothing happens. It has been working well for years, but then out of the blue it just won't open. I reinstalled it and the it still won't open. HELP! I'm under a big art deadline and this is ridiculous. Thanks.

    Or you may try to Move the folder or the Other options
    In the old days, deadlines were dead serious.

Maybe you are looking for

  • How Rock Guitar Legend Slash Hopes to Hack Music Discovery Apps

    Editor's Note: What do you guys think about the concept of apps helping artists with music discovery? Does it have legs? Is it monetizeable? Read and then let us know your thoughts on this thread.--ks http://thenextweb.com/insider/2014/03/10/sxslasha

  • Modified CRM application doesn't deployed in PROD server.

    Hello SDN! We have DEV and PROD runtime systems for CRM developing. Our custom CRM application successfully deployed to the DEV server many times. But transport to the PROD server hasn't any effect - our application doesn't exists in PROD server. In

  • Bug Report for Spellcheck-Since there is no other way, unless Mail crashes

    You can not close the spell check window with command-w. Mail will intiate the closing of the new message window currently being written or edited. And unlike 'Show Fonts' and 'Show Colors', the key command can not be used to close the window either.

  • I have no photos icon.  How can I get an icon?

    I have an iphone 4.  For some reason there is no icon for pictures to access my camera roll.  The only way I can get to my photos is through the camera.  I've tryed to reset my phone to factory settings, but still no pictures icon.  Please help.

  • Auto Create Filename from Form Fields

    Hello all, I am trying to find a way that I can save a form with a certain filename. I have the form create and all set to go. The user will be input some information into boxes. For instance I will have a Name box and a Date box. After the user is d