Skip to content
Advertisement

SQL query to find first six characters of the first name if the name is too short append $

Attached two images the first image is the question second image is the code that which I tried. I am stuck with append $ . I have even added my code

enter image description here

T-sql:

CREATE TABLE Tab1 (
tname VARCHAR (50)
);

INSERT INTO Tab1(tname)
VALUES ('Ravi Ashwin'),
('Mahendra Singh Dhoni'),
('Shikhar Dhawan');

Select a tname, substring (tname, 1,6) AS First_Sic_character, LEN (tname) AS Character_count,
     CASE WHEN LEN(tname) BETWEEN 0 AND 12 THEN 'SHORT & SWEET'
          WHEN LEN(tname) BETWEEN 13 AND 15 THEN 'MEDIUM & PREMIUM'
          WHEN LEN (tname) > 15 THEN ' LENGHTY$LOVELY'
END AS Category
From Tab1

Advertisement

Answer

Just try this:

CREATE TABLE #Tab1 (
tname VARCHAR (50)
);

INSERT INTO #Tab1(tname)
VALUES ('Ravi Ashwin'),
('Mahendra Singh Dhoni'),
('Shikhar Dhawan');

Select  tname,
LEFT(CONCAT(SUBSTRING(tname,0,CHARINDEX(' ',tname)),'$$$$$$'),6) AS First_Sic_character, LEN (tname) AS Character_count,
     CASE WHEN LEN(tname) BETWEEN 0 AND 12 THEN 'SHORT & SWEET'
          WHEN LEN(tname) BETWEEN 13 AND 15 THEN 'MEDIUM & PREMIUM'
          WHEN LEN (tname) > 15 THEN ' LENGHTY$LOVELY'
END AS Category
From #Tab1
DROP TABLE #Tab1
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement