Solved

I need help building a query that will parse data into a temp table

Posted on 2013-06-18
2
300 Views
Last Modified: 2013-06-20
Hi Experts,
I have an integrated service that imports raw data from a text file into a SQL Server table.  I want to build a temp table using a SELECT query that will give me a column with transaction amounts, by parsing the raw data starting at position 20 for a length of 13 characters.  Once parsed, the data looks like the samples below.  

I need to remove all leading 0's and then sum the amounts, and make the 2 right most characters decimals. How can I do this?  The raw data is originally imported to a varchar(250) column.


Sample of raw data:

0000000012500
00000000-1500
0000005200025
00000000-4500

The sum should be:  $52,065.25



Thanks in advance,
mrotor
0
Comment
Question by:mainrotor
2 Comments
 
LVL 69

Assisted Solution

by:Qlemo
Qlemo earned 250 total points
ID: 39256884
Many ways to do that, e.g.:
select sum(convert(money, substring(rawdata, patindex('%[-1-9]%', rawdata),100))/100) from 
(select rawdata = '0000000012500'
union all
select '00000000-1500'
) data

Open in new window

0
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 250 total points
ID: 39260101
I would convert to decimal only at the end, to avoid any rounding issues:


SELECT CAST( SUM( CAST(SUBSTRING(raw_data, PATINDEX('%[^0]%', raw_data), 100) AS bigint) ) / 100.0 AS decimal(19, 2))
FROM (
    SELECT '0000000012500' AS raw_data UNION ALL
    SELECT '00000000-1500' UNION ALL
    SELECT '0000005200025' UNION ALL
    SELECT '00000000-4500'
) AS test_data
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

735 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question