14

I have list of names of employees in a text file.

Instead of searching each name one by one, I want to search my database once for all the names of the text file. Some thing like:

select emplayeeID, Salary from employees where employee-name in "C:\myfile.txt"

Is it possible? If yes then what would be the SQL command for it? Thanks.

0

3 Answers 3

16

Yes, use OPENROWSET with BULK. You need a format file though.

select
    E.emplayeeID, E.Salary
from
    employees E
    JOIN
    OPENROWSET (
             BULK 'c:\myfile.txt',
             FORMATFILE = 'c:\myfileformat.txt'
    ) B ON E.name  = B.name 
Sign up to request clarification or add additional context in comments.

4 Comments

+1 sheeesh !! You always have those great ideas contradicting what I thought was the truth.... :-)
My friend, this is simply an awesome answer! +1 and if I could +10!
@marc_s, I guess we can all learn something new, even guys like you. I didn't figure you had anything left to learn my friend! :)
@gbn, if you have time, I opened a question that's a bit of a follow up to this one here, stackoverflow.com/questions/14710332/…, because I'm needing to pull the file from a shared drive.
8

No, it's not possible - at least not in a single command.
(see gbn's answer - if you want to, it is possible even in a single command....)

What you could do is this:

  • bulk load your employee names from the text file into a temporary table
  • then do a JOIN between your dbo.Employees table and that temporary bulk-load table you've just filled

To bulk insert your names, use something like:

BULK INSERT EmployeeNames
FROM 'c:\myfile.txt'
WITH
(FIELDTERMINATOR = ',',
 ROWTERMINATOR = '\n')

and then do your join:

SELECT e.EmployeeID, e.Salary 
FROM dbo.Employees e
INNER JOIN dbo.EmployeeNames en ON e.Name = en.Name

3 Comments

Let me try this. Is it necessary to include "WITH..." statement if my text file has only one column with single/first name of the employees??
@kamari: you need to tell bulk insert how your fields are separated (FIELDTERMINATOR=....) and how your rows (lines) are separated, yes
Yeah got it....i just did as you suggested and it worked fine for me....Thanks an lot marc.....
0

You could parse your text file into a comma separated string

select employeeID, Salary from employees where employee-name in ('Joe Blogs', 'Susan Smith', 'Jimi Hendrix')

A lot would depend on a) how big your text file is AND b) what platform you're using to construct your query.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.