Bulk Upgrade SQL Server C #

I have a database of 270 thousand rows with a primary key midand a column with a name value, and I have a text file with a middle and values. Now I would like to update the table so that each value is assigned to the correct middle.

My current approach is reading a text file from C # and updating a row in a table for each row read. There must be a faster way to do what I feel .. any ideas?

EDIT: There are other columns in the table, so I really need a way to update according to the middle.

+3
source share
2 answers

You can use the SQL Server Import and Export Wizard:

http://msdn.microsoft.com/en-us/library/ms141209.aspx

BULK TSQL:

BULK
INSERT YourTable
FROM 'c:\YourTextFile.txt'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO


SELECT * FROM YourTable
GO

, . , , FIELDTERMINATOR .

( ):

UPDATE RealTable
SET value = tt.value
FROM
  RealTable r
INNER JOIN temp_table tt ON r.mid = tt.mid
+7

SqlCommand?

    struct Item
    {
        public int mid;
        public int value;
    }

    public int Update(string connectionstring)
    {
        int res = 0;
        using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
        using (cmd.Connection = new System.Data.SqlClient.SqlConnection(connectionstring))
        {
            cmd.CommandText = @"UPDATE [table] SET [value] = @value WHERE [mid] = @mid;";
            cmd.CommandType = CommandType.Text;
            System.Data.SqlClient.SqlParameter mid = cmd.Parameters.Add("@mid", SqlDbType.VarChar);
            System.Data.SqlClient.SqlParameter value = cmd.Parameters.Add("@value", SqlDbType.VarChar);
            try
            {
                cmd.Connection.Open();
                foreach (Item item in GetItems("pathttothefile"))
                {
                    mid.Value = item.mid;
                    value.Value = item.value;
                    res += cmd.ExecuteNonQuery();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                cmd.Connection.Close();
            }
        }
        return res;
    }

    IEnumerable<Item> GetItems(string path)
    {
        string[] line;
        foreach (var item in System.IO.File.ReadLines(path))
        {
            line = item.Split(',');
            yield return new Item() { mid = int.Parse(line[0]), value = int.Parse(line[1]) };
        }
    }
+1

All Articles