Quantcast
Channel: T-SQL Question
Viewing all articles
Browse latest Browse all 5

T-SQL Question

$
0
0
Create Table #Foo(MyData varchar(20));
Insert #Foo(MyData) Values
('a*b*c*'),
('a*b'),
('a*b*c*d'),
('a*b*c*d*e*f');

;With cte As
(Select MyData, Len(MyData) - Len(Replace(MyData, '*', '')) As NbrOfStars
From #Foo)
Update cte
Set MyData = MyData + Replicate('*', 5 - NbrOfStars)
Where NbrOfStars < 5;

-- Check result
Select MyData From #Foo;

-- clean up
go
Drop Table #Foo;

Or if you just want to do a select that returns the correct number of *'s, but not update the table, then

;With cte As
(Select MyData, Len(MyData) - Len(Replace(MyData, '*', '')) As NbrOfStars
From #Foo)
Select MyData + Case When NbrOfStars < 5 Then Replicate('*', 5 - NbrOfStars) Else '' End 
From cte;
Tom

Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>