I have a file that has everything as nvarchar, including all the numbers, and there are no decimals, so '12.35' would just be stored as '1235'. Then I need it output with 4 decimal places.
I can't just divide and cast to decimal. It's ugly but this works.
SELECT CAST(CAST(rso.[NET_PRICE] AS Decimal(20,4)) / 10) AS Decimal(20,4) AS [Net Price]
SELECT CAST(CAST(rso.[Unit_Price] AS Decimal(20,4)) / 10000) AS Decimal(20,4) AS [Unit Price]
Is there a way to combine the CAST or something to make it more efficient? I have about 20 million records, and each record has about 40 of these, so they are eating up cycles.
1条答案
按热度按时间swvgeqrz1#
Short answer: No, there is not a better option.
Long answer: It depends what shall be the outcome and implicit versus explicit.
It all comes down what source data can be implicitly converted to "correct" values, even if the intermittent implicit conversions choose the most "appropriate" type. Which might not work for certain outlying values.
Simple test data and outputs shown:
Result is:
The third column shows where a calculation after the cast converted the type to something else than decimal 20 with 4 decimals.
However due to this structure of conversion code generation (in Excel) is really fast and I like Excel for function-copy-column-down for these tasks.
Final technical note: Use TRY_CONVERT or TRY_CAST when dealing with character columns as input to not fail in the middle of 20 million rows conversion work.