Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

Increment the string value letter by letter for every row using SQL server

5.00/5 (1 vote)
5 Oct 2011CPOL 13.7K  
Using SQL Server, we can increment the string value letter by letter for every row
This is my first post in this blog. Yesterday, my friend asked me to display the string value letter by letter using SQL server.

We have string function substring used here.
Below is the script for this:
SQL
use tempdb
go

if object_id(‘tempdb..#temp’) is not null
begin
   drop table #temp
end
go

– declaring the  variable to store the string
declare @test varchar(100)
set @test=’chaitanya’  -- assigning the value to the variable
declare @count int
select @count=len(@test)
declare @i int
set @i=1
create table #temp
(
   column1 varchar(100)
)
declare @result varchar(100)
declare @j int

set @j=0

while(@i <=@count)
begin
   select @result =substring(@test,@j,@i+1)
   insert #temp(column1)
   select @result
   set @i=@i+1
end

select  * from #temp


Result

c
ch
cha
chai
chait
chaita
chaitan
chaitany
chaitanya

Please let me know if you have any concerns or any suggestions!!

License

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