Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 List by Running Number

Author  Topic 

hayashiryo
Starting Member

46 Posts

Posted - 2013-10-02 : 22:46:27
Hi all.

I need help with a query.

I trying to generate a list of running numbers from a table. However the field is in varchar format and there may be missing numbers inbetween. Please see the example below


EMP-TABLE
Emp# Name
E1003 Matthew
E1004 Mark
E1007 Luke
E1009 John


Query I need to formulate.
I will input 1001 and 1010 as parameter.

Emp# AssignedTo
1001
1002
1003 Mattherw
1004 Mark
1005
1006
1007 Luke
1008
1009 John
1010


Thanks in advance.

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2013-10-02 : 23:44:48
[code]declare @emp_start int,
@emp_end int

select @emp_start = 1001,
@emp_end = 1010

; with emp_no as
(
select no = @emp_start, emp_no = 'E' + convert(varchar(4), @emp_start)
union all
select no = no + 1, emp_no = 'E' + convert(varchar(4), no + 1)
from emp_no
where no < @emp_end
)
select n.no, AssignedTo = e.emp_name
from emp_no n
left join emp e on n.emp_no = e.emp_no
[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page
   

- Advertisement -