I have a CHAR(250) field , which , for example will initially contain 10 byte data and 240 bytes of space, so remaining it has 250-10=240 bytes . Now I wanted to append a varchar of length say 20 bytes . So it will go to 240 + 20 =260 bytes which while inserting back to CHAR field will give size overflow issue.
Can do this , but I need the actual length , that means i want to re-pad the final string , ie 250 bytes in the final length ,
DECLARE @Var CHAR(250)='var lenght initial Data'
SELECT replace(@Var,' ','')
DECLARE @TempVar VARCHAR(20) = 'new text to be added'
SET @FinalVar=@Var + @TempVar
--Need to add final padding back to make it back to 250 bytes
Is there any other way rather counting and re-adding the space pads back ?
As you never tagged the DB that you have (as the sql
tag info says to do), so I'm assuming MySQL/MariaDB here...
The replace
is not really doing anything, but it seems that you want:
(and yes, no need to recount, by specifying a length)
DECLARE Var CHAR(250) default 'var length initial Data';
-- SELECT replace(@Var,' ',''); -- ... is not saved anywhere, so I removed.
DECLARE FinalVar CHAR(250);
SELECT CONCAT(Var, ' ', otherText) INTO FinalVar;
So, putting that into a function:
DELIMITER //
CREATE FUNCTION right_pad_spaces(otherText varchar(250)) RETURNS CHAR(250)
DETERMINISTIC
BEGIN
DECLARE Var CHAR(250) default 'var length initial Data';
DECLARE FinalVar CHAR(250);
SELECT CONCAT(Var, ' ', otherText) INTO FinalVar;
RETURN FinalVar ;
END; //
DELIMITER ;
Then use the function, RPAD the result with spaces, limited to 250 total length:
SELECT RPAD(right_pad_spaces('new text to be added'), 250, ' ') AS 'new string';
Output: (note the horizontal scroll bar)
Checking the length of the same call:
SELECT Length(
RPAD(right_pad_spaces('new text to be added'), 250, ' ')
) AS 'total length';
Gives:
Here's a dbfiddle with that handling.
Know that the site does not use DELIMITER
, so that was added for your local use.
So looks like there is no 'proper' fix to this but this is what I ended up with
DECLARE @Var CHAR(250)='var lenght initial Data'
SELECT @Var=replace(@Var,' ','')
DECLARE @TempVar VARCHAR(20) = 'new text to be added'
SET @FinalVar=@Var + @TempVar
SELECT @TempEmails= CAST(left(@FinalVar, 250) AS CHAR(250)) --CAST to char pads back to 250 , this is the easiest way
the Tweak is the CAST AS CHAR(250)
which will re-pad the string to 250
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.