Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can this code be written more efficiently?

Status
Not open for further replies.

outofservice

Technical User
Feb 20, 2002
33
GB

This code works but its messy and inefficient. Can you see a better way???


SELECT REPLICATE('0',LEN(n_num)-LEN(n_num+60)) + LTRIM(str(n_num+60))
FROM numbr
WHERE num_id=1
AND LEN(n_num)-LEN(n_num+60)>0
UNION
SELECT REPLICATE('0',0) + LTRIM(str(n_num+60))
FROM numbr
WHERE num_id=1
AND LEN(n_num)-LEN(n_num+60)<=0


Background information:

It takes the n_num column from the numbr table and increases the number by the set amount.
But if the number is prefixed by 0's (zero's) it puts them back on, or if the end number is the same length as the original numbers length, with any prefix, it does not put the prefix on. The same for if the number goes above the original length.

eg 00123 + 8 = 00131
00123 + 60 = 00183
00123 + 600 = 00723
00123 + 6000 = 06123
00123 + 60000 = 60123
00123 + 600000 = 600123

Thanks for your help!

Lauryn Bradley
SQL Server DBA
 
SELECT case when LEN(n_num)-LEN(n_num+60)>0 then
REPLICATE('0',LEN(n_num)-LEN(n_num+60))
else '' end + LTRIM(str(n_num+60))
FROM numbr
WHERE num_id=1

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top