SQLException : String or binary data would be truncated

前端 未结 12 714
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 06:41

I have a C# code which does lot of insert statements in a batch. While executing these statements, I got \"String or binary data would be truncated\" error and transaction r

相关标签:
12条回答
  • 2020-11-27 07:21

    In general, there isn't a way to determine which particular statement caused the error. If you're running several, you could watch profiler and look at the last completed statement and see what the statement after that might be, though I have no idea if that approach is feasible for you.

    In any event, one of your parameter variables (and the data inside it) is too large for the field it's trying to store data in. Check your parameter sizes against column sizes and the field(s) in question should be evident pretty quickly.

    0 讨论(0)
  • 2020-11-27 07:22

    Generally it is that you are inserting a value that is greater than the maximum allowed value. Ex, data column can only hold up to 200 characters, but you are inserting 201-character string

    0 讨论(0)
  • 2020-11-27 07:26

    This type of error occurs when the datatype of the SQL Server column has a length which is less than the length of the data entered into the entry form.

    0 讨论(0)
  • 2020-11-27 07:28
    1. Get the query that is causing the problems (you can also use SQL Profiler if you dont have the source)
    2. Remove all WHERE clauses and other unimportant parts until you are basically just left with the SELECT and FROM parts
    3. Add WHERE 0 = 1 (this will select only table structure)
    4. Add INTO [MyTempTable] just before the FROM clause

    You should end up with something like

    SELECT
     Col1, Col2, ..., [ColN]
    INTO [MyTempTable]
    FROM
      [Tables etc.]
    WHERE 0 = 1
    

    This will create a table called MyTempTable in your DB that you can compare to your target table structure i.e. you can compare the columns on both tables to see where they differ. It is a bit of a workaround but it is the quickest method I have found.

    0 讨论(0)
  • 2020-11-27 07:32

    In our own case I increase the sql table allowable character or field size which is less than the total characters posted from the front end. Hence that resolve the issue.

    0 讨论(0)
  • 2020-11-27 07:33

    It depends on how you are making the Insert Calls. All as one call, or as individual calls within a transaction? If individual calls, then yes (as you iterate through the calls, catch the one that fails). If one large call, then no. SQL is processing the whole statement, so it's out of the hands of the code.

    0 讨论(0)
提交回复
热议问题