简体   繁体   English

设置非数字,因为它们进入 null

[英]set Nonnumeric as they come in to null

I have a paymentHistory field that is an int that tracks how many payments have been made from the account before.我有一个 paymentHistory 字段,它是一个 int 字段,用于跟踪该帐户之前已支付了多少笔款项。 I have a source that is varchar for this field and someone enters 1.11 by accident on the front end.我有这个字段的 varchar 来源,有人在前端意外输入 1.11。 I can't change my source but I want to be able to allow only numeric and convert the non-numeric to null values.我无法更改源,但我希望能够只允许数字并将非数字转换为 null 值。 Can someone please give an example how I would convert values in this PaymentHistory column to only numeric or null.有人可以举个例子,我如何将此 PaymentHistory 列中的值转换为仅数字或 null。 Thanks!谢谢!

You can reject non-numeric values with a check constraint:您可以使用check约束拒绝非数字值:

alter table chk_paymenthistory add constraint chk_paymenthistory_num
    check (num not like '%[^0-9]%');

This only allows digits into the column.这只允许数字进入列。 But you don't want to reject the value, you want to replace it with NULL .但是您不想拒绝该值,而是想用NULL替换它。

If you are inserting the rows using insert , you can use try_cast() / try_convert() :如果您使用insert插入行,则可以使用try_cast() / try_convert()

insert into paymenthistory ( . . . )
    values ( . . ., try_cast(num as int), . . .);

This will convert the value to an integer (and you could use bigint or numeric instead).这会将值转换为 integer (您可以使用bigintnumeric代替)。 It will then be saved as a string -- but will be null if it is not a valid number.然后它将被保存为一个字符串——但如果它不是一个有效的数字,它将是null

That leaves you with a trigger for other situations.这让您可以触发其他情况。 But what other situation?但是还有什么情况? What comes to mind is bulk insert , but that doesn't invoke triggers by default.想到的是bulk insert ,但默认情况下不会调用触发器。 You can turn them on, if you want this functionality.如果您需要此功能,您可以打开它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM