Click here to Skip to main content
15,920,602 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more: , +
hello guys,


I want to find A input contains more than three repeating chars,please suggest me query for that.

ex:

Input=Acabacaga

i want restict the input shuld not containing more than three duplicate letter.upto 2 dullicate chr is ok..but i shold not contatin three or more dulicate letters.




Thanks in advance.

Rajshree V Lande.
Posted

Try this:
SQL
DECLARE @input VARCHAR(30) = 'Acabacaga'

;WITH CTE AS
(
    SELECT CONVERT(VARCHAR(1),LEFT(@input,1)) AS Letter, RIGHT(@input, LEN(@input)-1) AS Remainder
    WHERE LEN(@input)>1
    UNION ALL
    SELECT CONVERT(VARCHAR(1),LEFT(Remainder,1)) AS Letter, RIGHT(Remainder, LEN(Remainder)-1) AS Remainder
    FROM CTE
    WHERE LEN(Remainder)>1
    UNION ALL
    SELECT CONVERT(VARCHAR(1),Remainder) AS Letter, NULL AS Remainder
    FROM CTE
    WHERE LEN(Remainder)=1
)
SELECT Letter, ASCII(Letter) AS CharCode, COUNT(Letter) AS CountOfLetter
FROM CTE
GROUP BY Letter, ASCII(Letter)
HAVING COUNT(Letter)>2


Result:
Letter	CharCode	CountOfLetter
a			97			4


For further information, please see: Common Table Expressions[^]. In other words, CTE rocks!
 
Share this answer
 
Comments
Thanks7872 7-Oct-14 3:18am    
+5..!
Maciej Los 7-Oct-14 5:51am    
Thank you ;)
rajshreelande 7-Oct-14 8:18am    
THank you :)
Maciej Los 7-Oct-14 9:12am    
You're welcome ;)
rajshreelande 21-Oct-14 9:35am    
can u please suggest a query for dont allow three or more consicative letters in string .
EX:rahkkkff---dont allow
Hi Rajshree,

You can try this
SQL
SELECT len('acabacaga') - len(replace('acabacaga','a','')) As NoOfTimesACharacterIsRepeated.


You can store its output in a variable and pass the string type and the character to match as variables.

Regards,
Praneet
 
Share this answer
 
Comments
Maciej Los 7-Oct-14 2:53am    
OP wants to know how many times each letter is repeated. If it is higher then 2, it should be enumerated.
Would you like to say we need to check each letter in alphabet?
ALTER FUNCTION [dbo].[CheckValidString]
(
@input varchar(50)

)
RETURNS varchar
AS
BEGIN

declare @inputLength integer = datalength(@input);
declare @intIndex integer = 1;
declare @intMaxCount integer = 3;
declare @singleChar Char(1);
declare @isValid Char(1);
while (1 = 1)
begin
if @intIndex > @inputLength
begin
select @isValid = 'Y';
break;
end

select @singleChar = substring(@input, @intIndex, 1)

if(@inputLength - datalength(replace(@input, @singleChar, '')) > @intMaxCount)
begin
select @isValid = 'N';
break;
end
select @intIndex += 1;
end

RETURN @isValid
END
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900