问题
I have to CAST '-' (Hyphen Symbol) to Decimal(8,2) in sql server.
I am creating a CTE and dumping some data into a table with some columns. For 1 Column I need to dump '-' AS DECIMAL(8,2). How I will achieve this...
I am using
SELECT CAST('-' AS DECIMAL(8,2)) Column1
Which is throwing Error: Arithmetic overflow error converting varchar to data type numeric.
"I know the above query or casting cannot be done", but I need to achieve it somehow!! please help
I have couple of queries using which I am dumping a data into a physical table. Further to this, first query is the above which is creating a table with 4 columns. in col1 I need to put '-' symbol, which in other query is a decimal 'column'. Second query is inserting the data to the same physical table. there are some calculations happening during the fetching of the data from this dynamic created physical table. This is the reason, I need to convert '-' (Hyphen) into a Decimal column
回答1:
What's your base problem? You have a bad mapping.

We have strings we want to make into numbers. The problem is there is no number value for -
Therefore, you need to do something about it. The problem with your question, is that you haven't indicated what the code should do in cases of bad values.
- Do we blow up the process and stop storing data into the table? All or nothing might make sense
- Is there a sentinel value your system uses when dealing with "bad" data. Maybe -1 makes sense. This is the approach Gordon takes.
- Can we use a NULL in the place of the bad data?
- Should we just not insert those rows into our target table?
If you're using SQL Server 2012+, we have a TRY_CAST
method that will attempt to make the data type conversion and if it cannot, then the method returns a NULL.
There is a IsNumeric
function built into SQL Server but it's not 100% reliable (citation needed). Pair that with a CASE
expression and that would genericise Gordon's answer.
Otherwise, you'll need to add a filter to your source query to filter out those bad rows. I ran into a similar situation before with dates
回答2:
Presuming that you want to cast values in a column, then just use a case
statement to check for the hyphen:
SELECT (CASE WHEN col = '-' THEN CAST(0 AS DECIMAL(8,2))
ELSE CAST(col as DECIMAL(8, 2))
END) as column1;
You may need various forms of trimming, if there are spaces at the beginning or end.
来源:https://stackoverflow.com/questions/26061216/cast-hyphen-to-decimal