Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
im trying to read from a text file and use the id's inside the text file to update the status of the id's in a table to ok or whatever.

it reads the text file successfully and at the point to updating it throws the error
String or binary data would be truncated.


the id's in the text file looks like this:
1606873,1412393,1588593,1481673,1351153,1422153,1790433,1587033,1582593,1474233,1398953,1704553,1631313,1576513,1757113,1360193,1648393,1455473,1517753,1773633,1428153,1691553,1795793,1805113,1572513,1397353,1447473,1533393,1374273,1530353,1368233,1667313,1431793,1396953,1720633,1648633,1483753,1573993,1499673,1768273,1541193,1556673,1555793


alot more than this anyway.

What I have tried:

C#
private void btnTest_Click(object sender, EventArgs e)
{
   ReadFromTextFile();
}
public void ReadFromTextFile()
{
   StreamReader str = new StreamReader(@"C:\midMonth30072016\AppLog_Test.txt");
   while ((line = str.ReadLine()) != null)
   {
      updatestatus(line);
   }
}

public void updatestatus(string da)
{
   try
   {
      if (con.State != ConnectionState.Open)
      {
         con.Open();
      }
      SqlCommand cmd = new SqlCommand();
      string query = "update tblMidMonthold set Status='processed' where ID in ( @data )";
      SqlCommand sqlCmd = new SqlCommand(query, con);
      sqlCmd.Parameters.AddWithValue("@data", line);
      SqlDataReader dr = sqlCmd.ExecuteReader(); // it throws the arror at tis point.                                                       
   }
   catch (Exception)
   {
      throw;
   }
}
Posted
Updated 1-Aug-16 6:40am
v3
Comments
[no name] 30-Jul-16 11:47am    
Waht is the SQL-Type of ID exactly? Most probaly smaller the your actal data from Textfile.

It is not possible to add a list of integer for the SQL "IN" Operator as a single parameter.

One workaround is, you create the sql dynamically, something like this:
C#
private void button1_Click(object sender, EventArgs e)
{
    // Your sql
    string sql = "update tblMidMonthold set Status='processed' where ID in ( @data )";

    // your textfile data
    string line = "1606873,1412393,1588593,1481673,1351153,1422153";

    // Split text file data into list
    string[] numbers = line.Split(',');
    StringBuilder paramIntList= new StringBuilder();
    int dummyTryParse;
    // Check wheter all items are really numbers
    foreach (string number in numbers)
    {
        // Among TryParse also some other Validation on can add. I.e. empty
        // number items, max number of numbers(?) and maybe more.
        if (int.TryParse(number, out dummyTryParse))
        {
            if (paramIntList.Length > 0)
            {
                paramIntList.Append(",");
            }
            paramIntList.Append(number);
        }
        else
        {
            // Exeception or whatever you prefer in this error situation.
            throw new Exception("Try Parse faild. Value= "+ number);
        }
    }
    sql = sql.Replace("@data", paramIntList.ToString());
}

I hope it helps.

[Edit] Stringbuilder not necessary
C#
private void button1_Click(object sender, EventArgs e)
{
    // Your sql
    string sql = "update tblMidMonthold set Status='processed' where ID in ( @data )";

    // your textfile data
    string line = "1606873,1412393,1588593,1481673,1351153,1422153";

    // Split text file data into list
    string[] numbers = line.Split(',');

    int dummyTryParse;
    // Check wheter all items are really numbers

    // Check Input string
    foreach (string number in numbers)
    {
        // Among TryParse also some other Validation on can add. I.e. empty
        // number items, max numer of numbers(?) and maybe more.
        if (!int.TryParse(number, out dummyTryParse))
        {
            // Exeception or whatever you prefer in this error situation.
            throw new Exception("Try Parse faild. Value= "+ number);
        }
    }

    // Inputdata is ok (no axception in check part)
    sql = sql.Replace("@data", line);
}
 
Share this answer
 
v5
Comments
Emmablakes 31-Jul-16 6:14am    
thank you bro.....thank you... it perfectly solved my problem. you're the best bro.
[no name] 31-Jul-16 6:17am    
You are welcome bro :)
Maciej Los 1-Aug-16 12:06pm    
5ed!
[no name] 1-Aug-16 12:15pm    
Thank you very much Maciej.
Richard Deeming 1-Aug-16 13:18pm    
It would be better to add multiple parameters to the command, rather than injecting the data directly into the query.

In this specific case, you avoid SQL Injection because each value is parsed as an integer. But if the OP tries to reuse this code with strings, without realising the danger...

Alternatively, use Dapper[^], which handles cases like this automatically.
This Error occurred because of the Datatype of Status Column.

Quote:
String or binary data would be truncated.

when you try to assign a data to a column which is not capable of holding the data then the error will be thrown.

your status column's length might be less than 10 (nvarchar(5) )

Fix:

Increase the length of nvarchar/varchar type of the Status column and check. it should work.
Eg: nvarchar(50)
 
Share this answer
 
v2
Comments
[no name] 30-Jul-16 12:18pm    
I think the Problem is adding the list values for SQL IN as a Parameter.
Karthik_Mahalingam 30-Jul-16 12:42pm    
hi 0x01AA
i tried to reproduce the error by changing the nvarchar size, it thrown the same error as expected
I'd suggest to read this excellent article: Using comma separated value parameter strings in SQL IN clauses[^]
 
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