Mysql convert an int to MAC - mysql

I have some data that converts which has a 2 columns one column has IP and it contains values which are integers.I used the following function in my mysql query.Is there a function i can use to to convert my mac column which contains integers and data type is bigint to MAC address.
SELECT INET_NTOA(ip_address) AS myip,mymac
FROM table1

Assuming that you have stored the MAC address by suppressing all separators and converting the resulting HEX number into int, the conversion from this int to a human readable MAC address would be:
function int2macaddress($int) {
$hex = base_convert($int, 10, 16);
while (strlen($hex) < 12)
$hex = '0'.$hex;
return strtoupper(implode(':', str_split($hex,2)));
}
The function is taken from http://www.onurguzel.com/storing-mac-address-in-a-mysql-database/
The MySQL version for this function:
delimiter $$
create function itomac (i BIGINT)
returns char(20)
language SQL
begin
declare temp CHAR(20);
set temp = lpad (hex (i), 12, '0');
return concat (left (temp, 2),':',mid(temp,3,2),':',mid(temp,5,2),':',mid(temp,7,2),':',mid(temp,9,2),':',mid(temp,11,2));
end;
$$
delimiter ;
You can also do it directly in SQL, like this:
select
concat (left (b.mh, 2),':',mid(b.mh,3,2),':',mid(b.mh,5,2),':',mid(b.mh,7,2),':',mid(b.mh,9,2),':',mid(b.mh,11,2))
from (
select lpad (hex (a.mac_as_int), 12, '0') as mh
from (
select 1234567890 as mac_as_int
) a
) b

Just use HEX():
For a numeric argument N, HEX() returns a hexadecimal string representation of the value of N treated as a longlong (BIGINT) number.
Therefore, in your case:
SELECT INET_NTOA(ip_address) AS myip, HEX(mymac)
FROM table1
Note that this won't insert byte delimiters, such as colon characters.

Related

Finding the SUM of digits mapped to characters of a string

I have a table with 2 columns, one column with Alphabetic character and other column with value. Example
A 1
B 2
C 3
D 4
E 5
Now I would like to get the sum of all digits corresponding to characters containing in a string.
Like BAD = (2+1+4) = 7
Please suggest how this can be done in mysql (sql/procedure)
You can use the following solution:
I used the following to setup the table with the characters and their numeric values:
-- create the table for char values.
CREATE TABLE charValues (
charItem VARCHAR(1),
charValue INT
);
-- insert the values to the table.
INSERT INTO charValues VALUES
('A', 1),
('B', 2),
('C', 3),
('D', 4),
('E', 5);
To get the count of each character on your value, you can use the following FUNCTION (in this case named getCharCount). This FUNCTION was created on the following solution and can be used in this case to get the count of each character:
-- function to count the count of a character.
CREATE FUNCTION getCharCount (colValue VARCHAR(255), searchValue CHAR(1))
RETURNS INT DETERMINISTIC
RETURN (CHAR_LENGTH(colValue) - CHAR_LENGTH(REPLACE(colValue, searchValue, '')));
Now you can add a second FUNCTION to get the SUM of the value:
DELIMITER //
CREATE FUNCTION getStrSum (colValue VARCHAR(255))
RETURNS INT NO SQL
BEGIN
DECLARE retVal INT;
SELECT SUM(getCharCount(colValue, charItem) * charValue) INTO retVal FROM charValues;
RETURN retVal;
END //
Now you can use the following SELECT statement to get the calculated result based on table charValues. The functions can be used on the whole database like this:
SELECT getStrSum('BAD') -- output: 7
SELECT getStrSum('DAD') -- output: 9

MySQl Create Function to checking if string is correct

I try to create function in mysql. I want to check if the input string correct is (return 1) or not (return 0)
String ist correct when:
-has 3(big letters) to 8 symbols XXaZzzza:
- X are either A-Z or a-z or 0-9
- a could doesn't exsist or is a-z or A-Z
- Z is 0-9
- z could doesn't exsist or is 0-9
I know that code should be like this:
CREATE FUNCTION ID(ID INT)
RETURNS INT
BEGIN
DECLARE {CODE}
RETURN ;
END //
DELIMITER ;
But I don't now how to check this string at all
I tryed with:
CREATE FUNCTION ID(ID INT)
RETURNS char
BEGIN
DECLARE Num char;
IF NUM REGEXP '^([a-zA-Z0-9]{2}[0a-zA-Z]?[0-9][0-9]?[0-9]?[0-9]?[0a-zA-Z]?)' THEN Return "1";
ELSE Return 0;
END IF;
RETURN Num;
END;
But still doesn't work, Returns for all input "0"
You can do this with a regular expression:
select (str regexp '^[A-Z]{3}[a-zA-Z0-9]{2}[a-zA-Z]?[a-zA-Z0-9][0-9]{1,4}[a-zA-Z]?$')
Be sure the column has a case-sensitive collation, if you want to distinguish between upper and lower cases of characters.
Here is an example of it working.
Try a regular expresion in mysql. I´ve been testing it online, perhaps not quite there:
^([a-zA-Z0-9]{2}[0a-zA-Z]?[0-9][0-9]?[0-9]?[0-9]?[0a-zA-Z]?)
This regex checks for everything you stated except those 2 first conditions - 3 capital letters and 8 characters.
If you need user input on your query, use something like:
select regexp_like(:input, '^[a-zA-Z0-9]{2}[0a-zA-Z]?[0-9][0-9]?[0-9]?[0-9]?[0a-zA-Z]?$');
DROP FUNCTION IF EXISTS `test` $$
CREATE FUNCTION `test` (param INT) RETURNS INT(1)
BEGIN
IF EXISTS (select str regexp '^[A-Z]{3}[a-zA-Z0-9]{2}[a-zA-Z]?[a-zA-Z0-9][0-9]{1,4}[a-zA-Z]?$'
from (select param as str) x)
Then
return 1;
ELSE
return 0;
ENDIF

Summing a comma separated column in MySQL 4 (not 5)

I'm writing a query that selects data from one table into another, one of the columns that needs to be moved is a DECIMAL column. For reasons beyond my control, the source column can sometimes be a comma separated list of numbers. Is there an elegant sql only way to do this?
For example:
source column
10.2
5,2.1
4
Should produce a destination column
10.2
7.1
4
I'm using MySQL 4, btw.
To do this kind of non trivial string manipulations, you need to use stored procedures, which, for MySQL, only appeared 6 years ago, in version 5.0.
MySQL 4 is now very old, the latest version from branch 4.1 was 4.1.25, in 2008. It is not supported anymore. Most Linux distributions don't provide it anymore. It's really time to upgrade.
Here is a solution that works for MySQL 5.0+:
DELIMITER //
CREATE FUNCTION SUM_OF_LIST(s TEXT)
RETURNS DOUBLE
DETERMINISTIC
NO SQL
BEGIN
DECLARE res DOUBLE DEFAULT 0;
WHILE INSTR(s, ",") > 0 DO
SET res = res + SUBSTRING_INDEX(s, ",", 1);
SET s = MID(s, INSTR(s, ",") + 1);
END WHILE;
RETURN res + s;
END //
DELIMITER ;
Example:
mysql> SELECT SUM_OF_LIST("5,2.1") AS Result;
+--------+
| Result |
+--------+
| 7.1 |
+--------+
Here is a mysql function to split a string:
CREATE FUNCTION SPLIT_STR(
x VARCHAR(255),
delim VARCHAR(12),
pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '');
And u have to use it this way:
SELECT SPLIT_STR(FIELD, ',', 1) + SPLIT_STR(FIELD, ',', 2) FROM TABLE
Unfortunately mysql does not include string split functions or aggregates, so you will need to do this either in a stored procedure or on the client side.
A number table-based parse approach can be found at this SQLFiddle link. Esentially, once you have the substrings, the sum function will auto-cast the numbers. For convenience:
create table scores (id int primary key auto_increment, valueset varchar(30));
insert into scores (valueset) values ('7,6,8');
insert into scores (valueset) values ('3,2');
create table numbers (n int primary key auto_increment, stuffer varchar(3));
insert into numbers (stuffer) values (NULL);
insert into numbers (stuffer) values (NULL);
insert into numbers (stuffer) values (NULL);
insert into numbers (stuffer) values (NULL);
insert into numbers (stuffer) values (NULL);
SELECT ID, SUM(SCORE) AS SCORE
FROM (
SELECT
S.id
,SUBSTRING_INDEX(SUBSTRING_INDEX(S.valueset, ',', numbers.n),',',-1) score
, Numbers.n
FROM
numbers
JOIN scores S ON CHAR_LENGTH(S.valueset)
-CHAR_LENGTH(REPLACE(S.valueset, ',', ''))>=numbers.n-1
) Z
GROUP BY ID
;

mysql how to concat/append binary data type

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..
|| 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.
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));

Working with hex numbers in MySQL

I have a stored procedure that needs to convert hexadecimal numbers to their decimal equivalent. I've read the documentation for the UNHEX() function, but it is returning a binary value. What I'm wanting to do is something like this:
CREATE PROCEDURE foo( hex_val VARCHAR(10) )
BEGIN
DECLARE dec_val INTEGER;
SET dec_val = UNHEX( hex_val );
-- Do something with the decimal value
select dec_val;
END
What am I missing? How can I convert the UNHEX()'d value to a unsigned integer?
You can use the CONV() function to convert between bases.
SET dec_val = CONV(hex_val, 16, 10);
conv(hex_val, 16, 10)
Will convert a number of base 16 to base 10. The UNHEX function does something completely different, it converts pairs of hex digits to characters.
cast(conv(hex_val, 16, 10) as unsigned integer)
that should be solve the problem....