Note that there are some explanatory texts on larger screens.

plurals
  1. POStringToDecimal Function - T-SQL Question
    primarykey
    data
    text
    <p>I have some dirty input data that is being imported into a raw source table within SQL Server (2008 R2). Fields that are defined as decimal(9,2) or decimal(4,2) by the input provider are coming in as strings, however, the strings do not always conform to the data definition (go figure!).</p> <p>We import the data from flat files into the raw tables,then apply some conversion scripts to insert the 'cleaned' data into tables with the proper data types assigned to columns.</p> <p>For instance:</p> <pre><code>raw_table TotalAmount varchar(12) clean_table TotalAmount decimal(9,2) </code></pre> <p>Now, my question is this. If I want to do some 'basic' cleanup on this, I would want to do it in a function along the lines of:</p> <pre><code>CREATE FUNCTION [dbo].[StringToDecimal] ( @conversionString VARCHAR(12) ) RETURNS DECIMAL(9,2) AS BEGIN DECLARE @rsp DECIMAL(9,2) IF ISNUMERIC( LTRIM(RTRIM(REPLACE(@conversionString,' ',''))) ) = 1 BEGIN SET @rsp = ISNULL( CONVERT( decimal(17,6), NULLIF( LTRIM(RTRIM(REPLACE(@conversionString,' ',''))),'') ), 0 ) END ELSE BEGIN SET @rsp = 0 -- or we can return NULL here END RETURN @rsp END </code></pre> <p>However, how could one go about supporting various sized decimals in this mix? Is there a way to parametrize the response type? I considered just returning a decimal of the largest size we generally see, then converting it again on the other end, however, you run into arithmetic overflow issues.</p> <p>Would appreciate any thoughts/insight into solving this one!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload