Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey guys,

I've been trying to Search a table using the values I have on a text file, so far this is what I've got:
SQL
SELECT Username
FROM [TestEnvironment].[dbo].[TestComputerNameTable]
WHERE OPENROWSET (BULK 'C:\Users\svcacct.sepsql\Documents\SQL Scripts\usernames.txt', SINGLE_CLOB) MyFyle


I'm not getting anywhere right now.

Thanks,
Posted
Comments
virusstorm 2-Jul-15 12:31pm    
Do you need to do this via SQL? Could you simply parse the file using something like C# or VB.NET and search the table that way?

The OPENROWSET wasn't really designed for what you are trying to do in this example.
KatsuneShinsengumi 2-Jul-15 12:45pm    
Do you have sample code for c#? Something I can follow on? Because I haven't tried c# before.
virusstorm 2-Jul-15 12:46pm    
I can give you some sample code to do this. Give me about an hour to put something together and I'll post it as a solution.
KatsuneShinsengumi 5-Jul-15 23:44pm    
Thanks man.

1 solution

Assume you have a table like this:
SQL
CREATE TABLE dbo.Users
(
	Id INT NOT NULL,
	UserName VARCHAR(1000) NOT NULL,
	CONSTRAINT [PK_Users] PRIMARY KEY ([Id])
);


And assume you have a text file that looks like this (pipe delimited):
UserName|FirstName|LastName
testuser1|Test|User 1
testuser2|Test|User 2
testuser3|Test|User 3


The following code will search the table for each user in the file:
C#
string commandText = "SELECT * FROM dbo.Users WHERE UserName = @userName;";

using (StreamReader streamReader = new StreamReader(@"C:\Users.txt"))
{
    using (SqlConnection sqlConnection = new SqlConnection("data source=localhost;initial catalog=Scratch;integrated security=True;"))
    {
        using (SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection))
        {
            sqlConnection.Open();

            do
            {
                var line = streamReader.ReadLine();
                var userName = line.Split('|')[0];

                sqlCommand.Parameters.AddWithValue("@userName", userName);

                SqlDataReader dataReader = sqlCommand.ExecuteReader();

                while (dataReader.Read())
                {
                    //do something with the data
                }

                sqlCommand.Parameters.Clear();

            } while (!streamReader.EndOfStream);


            sqlConnection.Close();
        }
    }
}


Keep in mind, this is one of a dozen ways to achieve what you are trying to do.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900