Converts CRC16 MySQL function to SQL Server

420 Views Asked by At

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//
1

There are 1 best solutions below

2
On BEST ANSWER

Converting this function to Transact-SQL should be straightforward. In general:

  • Get rid of the definer, the backticks and DETERMINISTIC in the function header.
  • For loops, use WHILE condition BEGIN ... END. Notice a 'while' condition is the negation of a 'leave' condition.
  • Variable and parameter names must be prefixed with @.
  • Use decimal literals. (Use a calculator to convert the hexadecimals.)
  • Use = instead of := for variable assignment.
  • Replace >> 1 with / 2.
  • Replace LENGTH with LEN.
  • Replace ORD with ASCII or UNICODE.
  • Replace HEX(...) with CONVERT(char(4), CONVERT(binary(2), ...), 2), as suggested here.