SQLException : String or binary data would be truncated

前端 未结 12 711
被撕碎了的回忆
被撕碎了的回忆 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:10

    It could also be because you're trying to put in a null value back into the database. So one of your transactions could have nulls in them.

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

    Most of the answers here are to do the obvious check, that the length of the column as defined in the database isn't smaller than the data you are trying to pass into it.

    Several times I have been bitten by going to SQL Management Studio, doing a quick:

    sp_help 'mytable'
    

    and be confused for a few minutes until I realize the column in question is an nvarchar, which means the length reported by sp_help is really double the real length supported because it's a double byte (unicode) datatype.

    i.e. if sp_help reports nvarchar Length 40, you can store 20 characters max.

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

    With Linq To SQL I debugged by logging the context, eg. Context.Log = Console.Out Then scanned the SQL to check for any obvious errors, there were two:

    -- @p46: Input Char (Size = -1; Prec = 0; Scale = 0) [some long text value1]
    -- @p8: Input Char (Size = -1; Prec = 0; Scale = 0) [some long text value2]
    

    the last one I found by scanning the table schema against the values, the field was nvarchar(20) but the value was 22 chars

    -- @p41: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [1234567890123456789012]

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

    this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in that case: you specify transaction_status varchar(10) but you actually trying to store _transaction_status which contain 19 characters. that's why you faced this type of error in this code

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

    Simply Used this: MessageBox.Show(cmd4.CommandText.ToString()); in c#.net and this will show you main query , Copy it and run in database .

    0 讨论(0)
  • 2020-11-27 07:18
    BEGIN TRY
        INSERT INTO YourTable (col1, col2) VALUES (@val1, @val2)
    END TRY
    BEGIN CATCH
        --print or insert into error log or return param or etc...
        PRINT '@val1='+ISNULL(CONVERT(varchar,@val1),'')
        PRINT '@val2='+ISNULL(CONVERT(varchar,@val2),'')
    END CATCH
    
    0 讨论(0)
提交回复
热议问题