SQL Server 将变量 varchar 字段转换为金钱/小数/带小数位的内容
我正在寻找一种优雅的方法来将 varchar 类型的字段(其中包含变量数据)转换为可用于数学运算的数据类型 字段中的示例数据 (不包括引号)
''
'abc'
'23'
'23.2'
该方法应该适用于所有人,并且适用于第一个和第二个。第二个值应该返回 0,并且不会引发 SQL Server 错误。
I'm looking for an elegant way to convert a field of type varchar, with variable data in it, to a data type which can be used for mathematical operations sample data from the field
(excluding quotes)
''
'abc'
'23'
'23.2'
The method should work for all, and for the first & second values should return 0, and not throw an SQL Server error..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
你必须调整目标数据类型,我选择了decimal(18, 2)进行演示。
Try this:
You have to adjust the destination data type, I have chosen decimal(18, 2) for demonstration.
我知道这是一个早已死亡的线程,但我最近在谷歌搜索中偶然发现了它并产生了一个想法。它不如 CASE 语句优雅,但它是一种替代方案。
或者你可以这样做:
顶部版本会将“2 5”视为 2,底部版本会将其视为文本字段。
I know this is a long-dead thread, but I recently stumbled upon it from a Google search and had a thought. It is less elegant than a CASE statement, but it is an alternative.
or you could do:
The top version would see "2 5" as just 2, the bottom one would see it as a text field.
如果您想转换它,应该使用
UPDATE
而不是SELECT
If you'd like to convert it, you should use
UPDATE
instead ofSELECT
COALESCE
是一个很好的选择:查找更多信息此处。 它按顺序计算参数,并返回最初计算结果不为 NULL 的第一个表达式的当前值。ISNUMERIC
返回 0 或 1,具体取决于正在评估的值是否可以被视为 SQL“数字”或“数字”类型之一。例如 int、bigint、money..NULLIF
实质上查找您指定的值,如果匹配,则将其替换为NULL
值。CAST
只需将本示例中的一种数据类型更改为MONEY
如您所见,如果您使用此信息分解以下内容,我认为这是一个非常优雅的解决方案?
COALESCE
is a great option for this: Find more information here. It evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL.ISNUMERIC
returns 0 or 1 depending on if the value being evaluated could be considered one of the SQL 'number' or 'numeric' types. e.g. int, bigint, money..NULLIF
essentially finds the value you specify and if it matches it replaces it with aNULL
value.CAST
Simply changes a data type to another in this example toMONEY
As you can see, if you break the below down using this information its quite an elegant solution I think?