Friday, October 24, 2014

FIND EACH LETTER ASCII VALUE IN A GIVEN STRING

                                                   SIMPLE WAY

DECLARE @STR VARCHAR(MAX)='' 
SET @STR='FHJDGFHJSGDFJVFHHBHJSDF'
 ---PRINT @STR
 DECLARE @LEN INT
 CREATE TABLE #TEMP(ID INT IDENTITY ,STR_POSI VARCHAR(10),ASCII_VALUE INT)
 
 SELECT @LEN=LEN(@STR)
 DECLARE @I INT=0
 WHILE (@I<=@LEN)
 BEGIN
 
 INSERT INTO #TEMP SELECT STR_POSI=SUBSTRING(@STR,@I,1),ASCII_VALUE=ASCII(SUBSTRING(@STR,@I,1))
 
 SET @I=@I+1
 
 END
SELECT * FROM #TEMP

                                      IN STORED PROCEDURE


CREATE PROC USP_ASCII_VALUE
AS
BEGIN
   
      DECLARE @I INT=0
      DECLARE @LEN INT
    CREATE TABLE #TEMP(ID INT IDENTITY ,STR_POSI VARCHAR(10),ASCII_VALUE INT)
 
 SELECT @LEN=LEN(@STR)

 WHILE (@I<=@LEN)
 BEGIN
 
 INSERT INTO #TEMP SELECT   STR_POSI=SUBSTRING(@STR,@I,1),                                                                                                 ASCII_VALUE=ASCII(SUBSTRING(@STR,@I,1))
 
 SET @I=@I+1
 
 END
 SELECT * FROM #TEMP

EXEC  USP_ASCII_VALUE @STR='GVFDYVYbdagrugeurgwelL'


                               BY USING CTE TO FIND ASCII VALUE


DECLARE @STR VARCHAR(8000);
SET @STR = 'QOTHOBNSLFDNOWEAVNIVMNQPWF';

;WITH
TENS      (N) AS (SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL 
                  SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL 
                  SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0),
THOUSANDS (N) AS (SELECT 1 FROM TENS T1 CROSS JOIN TENS T2 CROSS JOIN TENS T3),
MILLIONS  (N) AS (SELECT 1 FROM THOUSANDS T1 CROSS JOIN THOUSANDS T2),
TALLY     (N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) FROM MILLIONS)
SELECT N, 
       LETTERASPOSITION = SUBSTRING(@STR, N, 1),
       ASCIIATPOSITION  = ASCII(SUBSTRING(@STR, N, 1))
  FROM TALLY 
 WHERE N <= DATALENGTH(@STR)
 ORDER BY N;



No comments:

Post a Comment