Monday, June 25, 2012

Long Lists of Comma Separated Values into One Long Line

I work a lot in Excel and SQL. Many times I'll receive a file from an internal resource or a vendor that looks similar to this:




Basically, they provide me with some sort of ID and then want me to append a bunch of other information based on that identifier. Most times that involves me getting those IDs into SQL so I can query the necessary table(s). One solution would be to import the file with the IDs. However, since these are usually ad hoc requests that doesn't usually make a lot of sense. What I've found to be easier is to build a string of these customer numbers and then put them in the where clause.

Here are the steps I follow. Create a version of each ID with a comma in Excel by using a formula such as

=A2 & ","

Then I will copy and paste that right into SQL. The problem is then you end up with something that looks a little bit like this:

select * from tbl where id in (30914,
43604,
34774,
11175,
99797,
52982)

Now there is nothing wrong with that query. It will execute as intended. However, let's say you have 1500 IDs? And already have 2,000 lines of code. When I'm in either of those situations I like to condense my list to one line.

So instead of copying from Excel right into SQL instead copy into Word (paste as unformatted text):


Then do a find on "^p" (without the quotes) and replace with a blank as shown below in the find and replace dialogue of Word.

What's left is the following:

select * from tbl where id in (30914,43604,34774,11175,99797,52982)

There might be a better way to do this, but it sure beats hitting delete + end for as many as records as there are in the set.

No comments:

Post a Comment