1

I am trying to write a stored function which will return BINARY(20) type. I would like to format this return value, by putting string, itn, float values in it. But I couldn't figure it out how can I append binary data.

CREATE FUNCTION `test`() RETURNS binary(20)
BEGIN
declare v binary(20);

set v:= CAST('test' as binary);
set v := v || cast(5 as binary); -- I would like to append 5 as binary but how?

return v;
END

First line writes test as binary, at second line I would like to append 5 as binary. How can I do that? Thank you all..

2 Answers 2

2

|| in mysql is logical OR - you want to use CONCAT:

SET v := CONCAT(v, CAST(5 AS BINARY));

instead of CAST(5 AS BINARY), you can use the shorthand BINARY 5.

Sign up to request clarification or add additional context in comments.

4 Comments

I tried that but it converts 5 to char, I also tried number 659845 instead of 5, it uses 6bytes instead of 4 bytes, so it is not binary.
what do you want the 5 to be converted to? BINARY means "byte string", so naturally an integer 5 is converted to the byte string '5'.
so did you make any progress in solving your problem? did you maybe figure out that packing different types into a BINARY string is not the best of ideas?
I confirmed this answer. Here I convert two strings to binary data, concatenate them, and then convert the result back to a string: select concat(binary 'x', binary 'y') as binary_return_value, cast(concat(binary 'x', binary 'y') as char) char_return_value;
0

To concat 5, rather than character 5, use char(5) rather than binary 5. So:

select concat("test", char(5))

returns a blob of 5 bytes. You can verify this with:

select length(concat("test", char(5))), hex(concat("test", char(5)));

To pad it out to a 20 byte array:

select convert(concat("test", char(5)), binary(20));

In your stored procedure, you just need:

set v:= concat("test", char(5));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.