I have this function for calculating crc16, but it is in MySQL, can someone help me convert to SQL Server?
I looked in several places, but I only find the crc32, this does not work for the generation of the PIX QRcode.
Below is an example of the function I have.
CREATE DEFINER=`root`@`%` FUNCTION `CRC16`( _STRING VARCHAR(25)) RETURNS varchar(50) CHARSET utf8mb4
DETERMINISTIC
BEGIN
DECLARE _myCRC integer;
DECLARE _ord INTEGER;
DECLARE _n Integer;
DECLARE _m Integer;
DECLARE _strlend Integer;
SET _myCRC := x'FFFF';
SET _n := 1;
SET _strlend := LENGTH(_STRING) ;
loop_crc: LOOP
IF _n > _strlend THEN
LEAVE loop_crc;
END IF;
SET _ord := ORD(SUBSTRING(_STRING, _n, 1) );
SET _myCRC := _myCRC ^ _ord;
SET _m := 0;
loop_bit: LOOP
IF _m = 8 THEN
LEAVE loop_bit;
END IF;
IF (_myCRC & x'0001') = x'0001' THEN
SET _myCRC := (_myCRC >> 1) ^ x'A001';
ELSE
SET _myCRC := _myCRC >> 1;
END IF;
SET _m := _m + 1;
END LOOP;
SET _n := _n + 1;
END LOOP;
return HEX(_myCRC);
END//
Converting this function to Transact-SQL should be straightforward. In general:
DETERMINISTIC
in the function header.WHILE condition BEGIN ... END
. Notice a 'while' condition is the negation of a 'leave' condition.@
.=
instead of :=
for variable assignment.>> 1
with / 2
.LENGTH
with LEN
.ORD
with ASCII
or UNICODE
.HEX(...)
with CONVERT(char(4), CONVERT(binary(2), ...), 2)
, as suggested here.