简体   繁体   中英

String or Binary Data Would be Truncated…

In my project I am generating a random character using the Random Number generator function and Storing it in the database, the number generates correctly but during insert of the data it is throwing the Exception “String or binary data would be truncated”

My code:

protected void trigger()
{  
    try
    {
        DataSet ds = ExamManagement.SP.table2_SP_Selectall().GetDataSet();
        if (ds.Tables[0].Rows.Count > 0)
        {
            string a = RandomNumberGenerator(4);
            string b = RandomNumberGenerator(4);
            string c = RandomNumberGenerator(4);
            ExamManagement.SP.table1_insert(a,b,c).Execute();
        }
    }
    catch (SqlException ex)
    {
        ClientMessaging("Error :"+ex);
    }
}

public static string RandomNumberGenerator(int length)
{
    System.Security.Cryptography.RandomNumberGenerator rng = System.Security.Cryptography.RandomNumberGenerator.Create();

    char[] chars = new char[length];

    //based on your requirment you can take only alphabets or number 
    string validChars = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXzZ";
    byte[] bytes = new byte[length-1];
    for (int i = 0; i < length; i++)
    {

        rng.GetBytes(bytes);

        Random rnd = new Random(bytes[0]);

        chars[i] = validChars[rnd.Next(validChars.Length)];

    }

    return (new string(chars));
}

My SQL Server Table Structure:

  Column1, nvarchar(100),null
  Column2, nvarchar(100),null
  Column3, nvarchar(100),null

My Altered Stored Procedure is,

   Create Procedure Table1_insert    
   (    
    @col1 varchar(max),    
    @col2 varchar(max),    
    @col3 varchar(max)   
   )    
  as    
 BEGIN    
 BEGIN TRY    
 Insert into Table1(Column1,Column2,Column3) values (@col1,@col2,@col3)    
END TRY    
BEGIN CATCH                    
IF @@TRANCOUNT > 0                    
ROLLBACK                    
DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int                    
SELECT @ErrMsg = ERROR_MESSAGE(),                    
@ErrSeverity = ERROR_SEVERITY()                    
RAISERROR(@ErrMsg, @ErrSeverity, 1)                    
END CATCH     
END

Check your stored proc. You probably forgot to specify the length on your parameters. Eg. @p1 nvarchar(1000)

The Column Variable Present in the DB is Smaller in Size than the Variable Data I have Sent to save So I got the Error String or binary data would be truncated

I had solved the error by Increasing the size of the Variable in DB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM