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

Time:02-21

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

CodePudding user response:

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

CodePudding user response:

use this

CONVERT(VARCHAR(6),tname  SUBSTRING('$$$$$$',LEN(tname),6))

CodePudding user response:

with cte(name) as(VALUES ('Ravi Ashwin'),
('Mahendra Singh Dhoni'),
('Shikhar Dhawan'))

select name,substring(name,1,6)
,(case when length(substring(name,1,6))<=6 then concat(name,'$') end )::varchar
,(case when length(name) between 0 and 12 then 'SHORT & SWEET' 
   when length(name) between 13 and 15 then 'MEDIUM & PREMIUM'
   when length(name)>15 then 'LENGHTY$LOVELY' end)Category
from cte
  • Related