[英]Converting varchar data type to decimals in SQL Server with stored procedure errors
A Quantity
column cannot be changed, it should be a decimal(18,5)
, and an older SSIS package would actually use VB code to do this 不能更改“ Quantity
列,它应该是decimal(18,5)
,并且较旧的SSIS包实际上将使用VB代码来执行此操作
Dim q As Decimal
q = Convert.ToDecimal(currentRow(16))
However, I am streamlining the process to import flat file into a new staging table 但是,我正在简化将平面文件导入到新暂存表中的过程
The value that is getting inserted into a database staging table is inserted as varchar(40)
. 将插入到数据库登台表中的值作为varchar(40)
插入。
Example of one of the values: 值之一的示例:
0000000191185.18200-
I want to convert that on the fly within a SQL Server query to a decimal(18,5)
value in order to insert it into another final table. 我想将其在SQL Server查询中即时转换为decimal(18,5)
值,以便将其插入到另一个最终表中。
Is it accurate to say that the conversion from varchar
to decimal(18,5)
should yield the value of -191185.18200 ? 准确地说,从varchar
到decimal(18,5)
18,5 decimal(18,5)
的转换应产生-191185.18200的值?
I am trying to test casting of this and I get an error in T-SQL 我正在尝试对此进行转换,但在T-SQL中遇到错误
select CAST(Quantity AS DECIMAL(18, 5))
from [DST].[DstPositionsStagingT]
Error is 错误是
Error converting data type varchar to numeric. 将数据类型varchar转换为数字时出错。
Quantity
is the column in the table holding the value. Quantity
是表中包含值的列。 What am I doing wrong? 我究竟做错了什么?
An example of embedding simple cleaning in the body of the SQL in the hope that it's easier to read. 在SQL主体中嵌入简单清除的示例,希望它更易于阅读。
SELECT
T.SecurityNumber,
SUM(clean.quantity) AS total_quantity,
SUM(CASE WHEN clean.quantity IS NULL THEN 1 END) AS failed_conversions,
MAX(T.Cusip) AS CUSIP
FROM
[DST].[DstPositionsStagingT] AS T
CROSS APPLY
(
SELECT CASE WHEN T.Quantity LIKE '%-'
THEN - TRY_CONVERT(DECIMAL(18,5), LEFT(T.Quantity, LEN(T.Quantity) - 1))
ELSE TRY_CONVERT(DECIMAL(18,5), T.Quantity )
END
)
AS clean(quantity)
GROUP BY
T.SecurityNumber
0000000191185.18200-
is not a valid format to convert to numeric. 0000000191185.18200-
不是要转换为数字的有效格式。 The valid format for negative value is -
sign should be on the left. 负值的有效格式为-
符号应在左侧。 You can shift the sign the left or remove the -
sign first convert to numeric and then add back 您可以将符号左移或删除-
符号先转换为数字,然后再添加回去
you can use case when
check for such case and convert accordingly 您可以case when
检查case when
使用案例并进行相应转换
declare @value varchar(20)
select @value = '0000000191185.18200-'
select case when right(@value, 1) = '-'
then -convert(decimal(18,2), replace(@value, '-', ''))
else convert(decimal(18,2), @value)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.