user1306004
user1306004

Reputation:

Mysql query to truncate data while inserting

I've created a table like this :

create table tbl(
address varchar(5000));

If i want to insert data in to the field address, if the length of data inserted exceeds the length of the field address. Then first truncate the the data and insert it in to address. please give me the correct query for the above problem....

Upvotes: 0

Views: 1656

Answers (2)

Andreas Wong
Andreas Wong

Reputation: 60584

I've tested on my mysql (5.5.8), create table as follows:

create table test ( a varchar(10) );

then insert

insert into test(a) values('1234567890112');

then select

select * from test;

gives me 1234567890

I think mysql will automatically truncate anything bigger you pass in to the field, so you don't need to worry, unless you need to log it in your application level everytime that happens

Upvotes: 1

Baz1nga
Baz1nga

Reputation: 15579

your insert/update query should probably call a method truncate which looks like this:

public static String truncate(String value, int length)
{
  if (value != null && value.length() > length)
    value = value.substring(0, length);
  return value;
}

Hope this helps.

Upvotes: 2

Related Questions