ISBN13 -> ISBN10
Here’s a handy function for converting a 13-digit ISBN to its 10-digit equivalent in SQL Server T-SQL.
CREATE FUNCTION TO_ISBN10 ( @isbn varchar(13) )
RETURNS VARCHAR(10)
AS
BEGIN
DECLARE @isbn10 varchar(10);
DECLARE @forwards int;
DECLARE @backwards int;
DECLARE @check int;
DECLARE @thisval int;
SET @isbn10 =substring(@isbn,4,9);
SET @forwards = 1;
SET @backwards = 10;
SET @check = 0;
WHILE @forwards <= 9
BEGIN
SET @thisval =cast(substring(@isbn10, @forwards, 1) AS INT)* @backwards;
SET @check = @check + @thisval;
SET @forwards = @forwards + 1;
SET @backwards = @backwards - 1;
END
SET @check = 11 -(@check % 11);
IF @check = 10 begin
SET @isbn10 = @isbn10 +'X';
END
ELSE BEGIN
SET @isbn10 = @isbn10 +cast(@check AS VARCHAR(1));
END;
RETURN @isbn10;
END