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
 General SQL Server Forums
 New to SQL Server Programming
 multiply each number in string

Author  Topic 

slimt_slimt
Aged Yak Warrior

746 Posts

Posted - 2009-10-01 : 15:15:50
hi,

i have following code:

select
'12345'
,left('12345',1) as c1
,left(right('12345',4),1) as c2
,left(right('12345',3),1) as c3
,left(right('12345',2),1) as c4
,right('12345',1) as c5
,cast(left('12345',1) as int) * 5
+cast(left(right('12345',4),1) as int) * 6
+cast(left(right('12345',3),1) as int) * 7
+cast(left(right('12345',2),1) as int) * 8
+cast(right('12345',1) as int) * 9

as sum_and_multiply


and i want in a string multiply 1number in string with a number for all numbers and sum everything.

is there another way to do this?

thank you for ideas.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-10-01 : 15:23:27
[code]SELECT SUM(SUBSTRING(@StrVal,number,1) * (4 + number))
FROM master..spt_values
WHERE type='p'
AND number >0
[/code]
Go to Top of Page

slimt_slimt
Aged Yak Warrior

746 Posts

Posted - 2009-10-01 : 15:34:07
visakh16, thank you. actually numbers to multiply are following (no order, no sequence):

select
'12345'
,left('12345',1) as c1
,left(right('12345',4),1) as c2
,left(right('12345',3),1) as c3
,left(right('12345',2),1) as c4
,right('12345',1) as c5
,cast(left('12345',1) as int) * 3
+cast(left(right('12345',4),1) as int) * 7
+cast(left(right('12345',3),1) as int) * 4
+cast(left(right('12345',2),1) as int) * 9
+cast(right('12345',1) as int) * 2
as sum_and_multiply
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-10-01 : 15:42:48
[code]
SELECT SUm(t.Digit * m.Val) as sum_and_multiply
FROM
(
SELECT SUBSTRING(@StrVal,number,1)*1 AS Digit,number
FROM master..spt_values
WHERE type='p'
AND number >0
AND number<=LEN(@StrVal)
)t
INNER JOIN(SELECT 3 AS Val,1 AS Ord
UNION ALL
SELECT 7,2
UNION ALL
SELECT 4,3
UNION ALL
SELECT 9,4
UNION ALL
SELECT 2,5)m
ON m.Ord=t.number
[/code]
Go to Top of Page
   

- Advertisement -