Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

sql - 如何避免SQL中的“被零除”错误?(How to avoid the “divide by zero” error in SQL?)

I have this error message:

(我有此错误信息:)

Msg 8134, Level 16, State 1, Line 1 Divide by zero error encountered.

(消息8134,级别16,状态1,第1行除以零错误。)

What is the best way to write SQL code so that I will never see this error message again?

(编写SQL代码以使我再也看不到此错误消息的最佳方法是什么?)

I could do either of the following:

(我可以执行以下任一操作:)

  • Add a where clause so that my divisor is never zero

    (添加一个where子句,这样我的除数永远不会为零)

Or

(要么)

  • I could add a case statement, so that there is a special treatment for zero.

    (我可以添加一个case语句,以便对零进行特殊处理。)

Is the best way to use a NULLIF clause?

(是使用NULLIF子句的最佳方法吗?)

Is there better way, or how can this be enforced?

(有没有更好的方法,或者如何执行?)

  ask by Henrik Staun Poulsen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to avoid a "Division by zero" error we have programmed it like this:

(为了避免出现“被零除”错误,我们对此进行了如下编程:)

Select Case when divisor=0 then null
Else dividend / divisor
End ,,,

But here is a much nicer way of doing it:

(但这是一种更好的方法:)

Select dividend / NULLIF(divisor, 0) ...

Now the only problem is to remember the NullIf bit, if I use the "/" key.

(现在唯一的问题是,如果我使用“ /”键,则要记住NullIf位。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...