Transact SQL :: Divide By Zero Error

Oct 25, 2015

I have an equation 

( ( P.RealisedConsumption / ( NULLIF(( PO.ActualQty * P.QuantityPO ), 0) / NULLIF(1000000, 0) ) ) - 1 ) * 100 AS FibreScrapFactor

This works for the example order that I am looking at.  However if i take out the where clause (so i have all orders) i get divide by zero error.  

If I limit the / 1000000 to 10 which i then have 

( ( P.RealisedConsumption / ( NULLIF(( PO.ActualQty * P.QuantityPO ), 0) / NULLIF(10, 0) ) ) - 1 ) * 100 AS FibreScrapFactor

This works for all orders, but is incorrect I need to divide by a million.  How can I get this to work?

View 3 Replies


ADVERTISEMENT

Transact SQL :: Divide By Zero Error Encountered

Jun 18, 2015

My Code is

SELECT    Client,State,    
CASE WHEN Weight>=11 and Weight<=455 and Height>=110 and Height<=250
  THEN isnull((cast(nullif(Weight,0)/power((NullIf(Weight,0)/100),2) as int)),0) else -1 end as BaseBMIScore
FROM Test100 

And I got following error:

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

View 4 Replies View Related

Transact SQL :: Divide By Zero Error In Empty Function

Oct 9, 2015

I have a work database where I implemented a table-valued function. One colleague of mine reported to me that this function gave a Divide by Zero error when executed with some specific values given to its arguments (there are a 15 arguments). Then I started debugging, and I introduced some exit points to the function before its end in order to detect the point where the error appeared, since I don't have access to the database server and I cannot use the debugging tools from remote, due to the network configuration of my office. I can only do attempts on the code to try to find a solution.

Since I didn't manage to get rid of this error, I decided to make a silly and desperate attempt: I put a RETURN statement immediately after the BEGIN of the function body, with the idea that the function should not raie any error if it exit immediately after its beginning, despite the fact that this results in an empty table in return.

The result of my attempt is that the Divide by Zero error is still THERE (!), even if my function looks like

ALTER FUNCTION [dbo][<myFuncName>](...parameters...) RETURNS TABLE (...table definition...) AS BEGIN 
RETURN
END 
GO

How I can check it.

View 5 Replies View Related

Transact SQL :: How To Get Percentahe Profit Without Error In Zero Divide

Nov 4, 2015

How can I get the value (pr_profit / pr_sales ) * 100,  (cur_profit / cur_sales) * 100 for %profit. When I am giving zero devide error  is coming . How can I give  if pr_profit = 0 then % profit should be zero.

SELECT  
SUM(CASE WHEN invdate >= {d '2015-01-01' } and invdate <={d '2015-11-03' } Then linetotal Else 0 End) as cur_Sales,
SUM(CASE WHEN invdate >={d '2014-01-01' } and invdate <= {d '2014-11-03' } Then linetotal - linecost Else 0 End) as pr_Profit,
SUM(CASE WHEN invdate >= {d '2015-01-01' } and invdate <={d '2015-11-03' } Then linetotal - linecost Else 0 End) as cur_Profit,
SUM(CASE WHEN invdate >= {d '2015-01-01' } and invdate <={d '2015-11-03' } Then linetotal - linecost Else 0 End) -

[code]...

View 5 Replies View Related

Transact SQL :: How To Use Divide Function In Query

Jun 9, 2015

When I am doing the divide all values are showing Zero.

DECLARE @test_sample TABLE (ClientID VARCHAR(5), FiscalYear varchar(4), QtrNumerator int, QtrrDenominator int)
INSERT INTO @test_sample VALUES
('ABC','2014',0,100),
('ABC','2015', 10,40),
('CDE','2013',14,0),
('CDE','2012',20,50)
select QtrNumerator/nullIf(QtrrDenominator,0) as QTR from @test_sample

and also I want to show the  QTR with %, for example, 66.57%

View 6 Replies View Related

Transact SQL :: Divide A Number By Field And Date

Jul 7, 2015

I have this rows as result of my query:

aaaaa     bbbbb       date        result
-------     -------      --------    ---------
a            100          7-7-15
a            100          7-7-15
a            100          8-7-15
b            200          7-7-15
b            200          8-7-15
b            200          8-7-15

I need this (divide bbbbb by row count as result, group by "aaaaa and date":

aaaaa     bbbbb       date        result
-------     -------      --------    ---------
a            100          7-7-15       50
a            100          7-7-15       50
a            100          8-7-15      100
b            200          7-7-15      200
b            200          8-7-15      100
b            200          8-7-15      100

Can I do it?

My SQL Code is

(date=FEC, RESULT=COSTECUB, aaaaaa=TRACTA, bbbbb=TRAPR3)  :
SELECT VTRA00F.TRACTA, ACRDES, TRAPRL, TRAPR1, TRAPR2, TRAPR3,
CASE WHEN TRAPR3 IS NULL THEN
(CASE WHEN (ALLQDE+ALLQCN+ALLQCR+ALLQMR+ALLQNN+ALLQNR+ALLQV1+ALLQV2) <= TRAPRL THEN (TRAPR1*(ALLQDE+ALLQCN+ALLQCR+ALLQMR+ALLQNN+ALLQNR+ALLQV1+ALLQV2)) ELSE (TRAPR2*

[Code] .....

View 8 Replies View Related

Transact SQL :: How To Divide Amount By Cash And Credit Card

Nov 19, 2015

I have typed a query by combining multiple tables to show sum of TotalReceivedAmount by MRN. It also have payment mode which is paid by cash or credit card. Now the query shows the sum for MRN combining all the payment done by credit card and cash. How am I supposed to show the amount paid by credit card and cash separately?

Here is the query :

SELECT Distinct     dbo.CA_Payment.MRN, dbo.CA_Patient.FirstName, dbo.CA_PaymentModeMaster.Description AS PaymentMode, 
CASE (dbo.CA_Payment.PaymentModeID) WHEN 2 THEN dbo.CA_Payment.CardNumber END AS CreditCardNumber, CASE (CA_Registration.PatientTypeID) 
WHEN 1 THEN dbo.CA_PatientTypeMaster.Description WHEN 2 THEN dbo.CA_DebtorMaster.DebtorName END AS Debtor, 

[Code ....

View 6 Replies View Related

Divide By Zero Error

Feb 24, 2006

Hello,

When I execute the following query, I get a Divide by zero error. I believe the Divide By zero error is occuring in the following statement. How do I avoid the error?


ModelDiff = CONVERT(decimal (8, 4), abs(yest.ModelValue-today.ModelValue)/abs(yest.ModelValue))


drop table #MaxArchiveDates
DECLARE @MaxArchiveDate INTEGER
, @EdgeModelID INTEGER
, @DefinitionID INTEGER
SELECT ArchiveDataDate = MAX(ArchiveDataDate) INTO #MaxArchiveDates FROM intldbArchive.dbo.GOModelUniversesSaveD
UNION SELECT ArchiveDataDate = MAX(ArchiveDataDate) FROM intldbArchive.dbo.GOSecurityGroupModelValSaveD
UNION SELECT ArchiveDataDate = MAX(ArchiveDataDate) FROM intldbArchive.dbo.GOSecuritiesSaveD
UNION SELECT ArchiveDataDate = MAX(ArchiveDataDate) FROM intldbArchive.dbo.GOUniverseSecurityMembeSaveD
SELECT @MaxArchiveDate = MIN(ArchiveDataDate) FROM #MaxArchiveDates
SELECT @MaxArchiveDate
SELECT ModelID = today.ModelID
, RelativeUniverseID = today.RelativeUniverseID
, SecurityID = today.SecurityID
, ModelValueT = CONVERT(decimal (8, 4), today.ModelValue)
, ModelValueY = CONVERT(decimal (8, 4), yest.ModelValue)
, ModelDiff = CONVERT(decimal (8, 4), abs(yest.ModelValue-today.ModelValue)/abs(yest.ModelValue))
FROM OptMod.dbo.GO_SecurityGroupModelValues today
JOIN intldbArchive.dbo.GOSecurityGroupModelValSaveD yest
ON today.SecurityID = yest.SecurityID
AND today.ModelID = yest.ModelID
AND yest.ArchiveDataDate = @MaxArchiveDate

Thanks in advance!!!
sqlnovice123

View 1 Replies View Related

Divide By Zero Error

Feb 28, 2006

I am writing a report that deals with time in seconds. I am trying to figure out the average handle time for each call.
To Get this number i use 5 fields. the formula is

(((cs_acd_trk_t + cs_acd_ext_c)/(cs_acd_trk_c + cs_acd_ext_c)) + ((cs_t_acd_wrk)/(cs_acd_trk_c + cs_acd_ext_c))/(cs_acd_trk_c + cs_acd_ext_c))

Which translates to ((Incoming Handle Time) + (Work))/(Number of Incoming Calls)

When it does the calculations some times the cs_acd_trk_c + cs_acd_ext_c (number of incoming calls) is zero.

I dont know how to get around this ... i tried to set that value to <>0 in my query but it threw my other numbers off for number of calls which is a different value on the report.
Any Help on this would be super appreciated.
Thanks,
Mitch

View 2 Replies View Related

Divide By Zero Error Only With Top

Sep 27, 2006

In the following expression, the query executes with no errors (there are sometimes 0's and nulls in IRON and ENERGY):

SELECT * FROM gff2vg

WHERE (gff2vg.ENERGY > 0 and gff2vg.IRON > 0)

order by IRON/ENERGY desc

but when TOP is added there is a divide by zero error. Is there a way to avoid this?

SELECT TOP(64) * FROM gff2vg

WHERE (gff2vg.ENERGY > 0 and gff2vg.IRON > 0)

order by IRON/ENERGY desc



Thanks.

View 7 Replies View Related

#Error Using IIF And Divide By Zero

Jan 19, 2007

I am getting an error in a calculated field that could potentially divide by zero, even though I'm using an IIF. The column displays in the report as "#Error". My expression looks like this:


= IIF(Fields!Qty.Value = 0, "None", Fields!Hours.Value / Fields!Qty.Value)

I have successfully used this approach with INT fields, but this time the Hours field is a NUMERIC(9,2). My workaround is to do this:


IIF(Fields!Qty.Value = 0, "None", IIF(Fields!Qty.Value = 0, 42, Fields!Hours.Value) / Fields!Qty.Value)
I guess the 42 is cast to an INT inside the second IIF and the calculation works.
What's strange is that the division would even be carried out in the event of Qty = 0 from the first IIF, because the expression should just evaluate to "None" and that would be that.
Has anybody run into this problem? Is my workaround the recommended approach?
-Larry

View 14 Replies View Related

Divide By Zero Error SQL SERVER

Jul 31, 2006

Hi
Is there a way to prevent this error?
I'm getting it from query line:
10000 * (SELECT count(filial_cotacao) from negocios_cotacoes where filial_cotacao = cod_filial)) / (22 * 6 * (SELECT count(filial_cotacao) from negocios_cotacoes where filial_cotacao = cod_filial)),1) 'Atingimento Semestre'
Thanks a lot

View 2 Replies View Related

OLAP - Divide By Zero Error??

Sep 5, 2001

Some of my calculated members look like "######" in Excel and I believe it is because of divide by zero errors. I have tried right clicking on the table, selecting "Table Options" and "For error, values, show:" I have enter 0. This is not working.
Does anybody know how to get rid of this.

Thanks,
Ruaidhri.

View 1 Replies View Related

Divide By Zero Error Encountered

Oct 31, 2013

I have one table with columns patientName , Nurse,ArrivalDate, DepartDate . It has all the patiet information for all the Nurses.

I am calculating Average Number of patients per day per nurse by using below query

SELECT Nurse,
COUNT(DISTINCT patientName) AS NoOfPatients,
COUNT(DISTINCT patientName) * 1.0/COUNT(DISTINCT ArrivalDate) AS [AvgNo.ofpatientsPerDay]
FROM Table t
GROUP BY NURSE

but if ArrivalDate is Null I am getting below error saying that Divide by zero error encountered.

View 5 Replies View Related

How To Avoid Divide By Zero Error

Nov 6, 2013

I have some SQL scripts for SQL Views and getting divide by zero error. I am using

COALESCE(Field1,Field2,1)/COALESCE(Field3,Field4,1)

This function can avoid NULL but how I can avoid 0 ?

Is there any function in SQL that can take care both NULL and 0 and replace it with 1.

View 5 Replies View Related

Divide By Zero Error Encountered.

Dec 3, 2007

How can i handle this kind of error in my execution of my storedprocedure? Error:Divide by zero error encountered.

thanks!

Funnyfrog

View 3 Replies View Related

Divide By Zero Error Trapping

Jul 20, 2005

I have the following line in a select statement which comes up with adivide by zero error.CAST(CASE Splinter_StatusWHEN 'SUR' THEN 0ELSE CASE WHEN Sacrifice>=1THEN 3*m.Premium/100-(m.Sacrifice * 3*m.Premium/100)/(m.Gross+m.Sacrifice)ELSE 0ENDEND AS Float)AS Bond2,The error happens on the section (m.Gross + m.Sacrifice) as this canequal zero and throws out the part of the calc that divides by it. Itis correct in some instances that it does so. The full SQL statementhas a large number of these expressions so I need a method I can applyto any line if possible.I know that it is mathmatically correct to error where this value iszero, but what I want to do is set the output of the entire expressionto zero if there is an error.Realistically an error such as this could happen at a few points inthe expression (or one of many others), so I need to find a way ofcatching any error in the expression and setting the return value to0. I thought of using a CASE statement, but wondered if there was abetter way of looking at this as the case statement would have tocheck each variation where it could throw an error.Any ideas ?ThanksRyan

View 3 Replies View Related

Wht Does This Give Divide By 0 Error?

May 24, 2007

I am using iif which works just fine in Access to prevent divide by zero errors but this:



=iif(Fields!oh_ret.Value<>0,(Fields!oh_ret.Value-Fields!oh_cost.Value)/Fields!oh_ret.Value,"")



Fails



As Does:





=iif(Fields!oh_ret.Value=0,"",(Fields!oh_ret.Value-Fields!oh_cost.Value)/Fields!oh_ret.Value)



Why? How do I get around this?

View 4 Replies View Related

T-SQL (SS2K8) :: Eliminating Divide By Zero Error

Oct 21, 2014

Being one step removed from innumerate, I was wondering whether there was a more elegant way to avoid divide by zero error instead of trudging through a bunch of isnulls.

My intuition tells me that since multiplication looks like repeated addition, that maybe division is repeated subtraction?
If that's true is there a way to finesse divide by zero errors by somehow reframing the statement as multiplication instead of division?

The sql statement that is eating my kishkas is

cast(1.0*(
(ISNULL(a.DNT,0)+ISNULL(a.rex,0)+ISNULL(a.med,0))-(ISNULL(b.dnt,0)+ISNULL(b.rex,0)+ISNULL(b.med,0))/
ISNULL(a.DNT,0)+ISNULL(a.rex,0)+ISNULL(a.med,0)) as decimal(10,4)) TotalLossRatio

Is there a way to nucleate the error by restating the division? My assertion underlying this statement is that the a alias represents a premium paid, so between medical, pharmacy and dental, there MUST BE at least one premium paid, otherwise you wouldn't be here. the b alias is losses, so likewise, between medical, pharmacy and dental, there MUST BE at least one loss (actually, it just occurred to me that maybe there are no losses, but that would be inconceivable, but ill check again)) so that's when it struck me that maybe there's a different way to ask the question that obviates the need to do it by division.

View 6 Replies View Related

Reporting Services :: Divide By Zero Error

Apr 15, 2015

I have SSRS 2012 and have a report with an expression shown below.  I am getting an error of

"[rsRuntimeErrorInExpression] The Value expression for the textrun ‘Textbox133.Paragraphs[0].TextRuns[0]’ contains an error: Attempted to divide by zero."

Textbox 133 has an expression as shown below and I cannot figure out why I get the error because I thought the IIF would bypass divide by zero.

=IIF(Sum(Fields!PriorQty.Value) = 0.0, 1,(Sum(Fields!CurrentQty.Value) - Sum(Fields!PriorQty.Value)) / Sum(Fields!PriorQty.Value))

View 10 Replies View Related

Getting Error When Divide By Zero For Percent Increase

May 8, 2008

Does anyone know how to get over their dreadfull divide by zero error. I keep getting the error, i have changed this code so much. I need to get the percent increase from 2007-2008 ("Total") in this table grouping. I know im getting the error in some of the fields, because sometimes the total is 0 and sometimes the 2007 is 0. What do i do?





Code Snippet

=IIF(Sum(iif(Fields!Column_Text.Value = "Total", Cdbl(Fields!Period_1.Value), 0.0))=0,"0%",
Sum(iif(Fields!Column_Text.Value = "Total", Fields!Period_1.Value,nothing))- Sum(iif(Fields!Column_Text.Value = "2007", Fields!Period_1.Value, nothing)))/ IIF(Sum(iif(Fields!Column_Text.Value = "2007", Fields!Period_1.Value, nothing))=0,1,Sum(iif(Fields!Column_Text.Value = "2007", Fields!Period_1.Value, nothing)))

View 1 Replies View Related

Workaround Divide By Zero Error Encountered Message

Jan 7, 2004

Hey all,

When i exec an sp it runs a sum, sometimes it is possible that there is a 0 value, it then returns an error Divide by zero error encountered
How can i work around this error

My sp code is

CREATE proc CP_avgloss_rings
@mID varchar(10),
@startdate datetime,
@enddate datetime
as
select ((sum(vtp)-(sum(moneyout)))/100) / ((sum(playtime))/ 3600) as avgloss
from dbo.rings
where
machineID = @mID
and convert(varchar,njdate,121)
between convert(varchar,@startdate,121)
and convert(varchar,@enddate,121)
GO


Maybe someone can help me
Cheers Wimmo

View 4 Replies View Related

Divide By Zero Error Encountered - Null Value Eliminated

Mar 19, 2015

I'm getting this error:

Divide by zero error encountered.
Warning: Null value is eliminated by an aggregate or other SET operation.

this is where i'm getting the error:

CASE WHEN Claims.ClaimTotal > 0 then (ISNULL(Claims.ClaimTotal,0) / ISNULL(TotalPrem.TotalPrem,dbo.TrnPolicy.TotalDue)) else 0 END AS LossRatio

View 3 Replies View Related

Divide By Zero Error Encountered. Error

Mar 17, 2008

the query is below ;

Select Model, Kota as [Çıkan Anket]
,
(Select Count(*) From dbo.Main Where RuhsatSahibiModel = tt.Model) as [Verilen Adres] , (Select Count(RuhsatSahibiSahisID) From dbo.Main Where DurumKoduID in(1,2,3,4,5,6,9,12,13,14,15,16,17,20,21,22,23,24,25,26,27,28) and RuhsatSahibiModel = tt.Model) as [Donen Adres]

,

(Select Count(*) From dbo.Main Where DurumKoduID = 2 and RuhsatSahibiModel = tt.Model) as [Donen Anket] ,((Select cast(Count(*) as decimal(2,0)) From dbo.Main Where DurumKoduID = 2 and RuhsatSahibiModel = tt.Model ) / (Select top 1 (cast(Kota as decimal(2,0))) From dbo.Model Where Model = tt.Model))*100 as [Oran]

,

(Kota - (Select Count(*) From dbo.Main Where DurumKoduID = 2 and RuhsatSahibiModel = tt.Model)) as [Kalan Anket] , ((Select Count(*) From dbo.Main Where RuhsatSahibiModel = tt.Model)- (Select Count(RuhsatSahibiSahisID) From dbo.Main Where DurumKoduID in(1,2,3,4,5,6,9,12,13,14,15,16,17,20,21,22,23,24,25,26,27,28) and RuhsatSahibiModel = tt.Model)) as [Kalan Adres]

From

(SELECT Model, SUM(Kota) AS Kota FROM dbo.Model GROUP BY Model) as tt where tt.Model in('A3')



it's returning error message : "Divide by zero error encountered."

View 3 Replies View Related

Divide By Zero

Jul 27, 2001

I have a field that divides one field by the sum of two others. However, when both of the two latter fields are 0's, I get a divide by zero error and the output halts. How do I get this so that for these records I put a NULL or UNDEFINED or something in there at least so I can see the rest of the output. Thanks.

View 1 Replies View Related

How To Get Around Divide By Zero

May 1, 2008

I have this sql posted below which sometimes gets a divide by zero error. How can you get around this error please

SELECT
COUNT(DISTINCT dbo.safety_obs_data.form_id) AS TotalObs,
SUM(dbo.safety_obs_data.safe) AS TotalSafe,
SUM(dbo.safety_obs_data.unsafe) AS TotalUnsafe,
CONVERT(decimal(18, 2), (SUM(CASE WHEN (safe) * 100.0) / (SUM(safe) + SUM(unsafe)))AS [% Safe],
SUM(CASE WHEN unobserved = 1 THEN 1 ELSE NULL END) AS NotSeen,
SUM(CASE WHEN made_safe = 1 THEN 1 ELSE NULL END) AS TotalMadeSafe,
SUM(CASE WHEN sap_note = 1 THEN 1 ELSE NULL END) AS TotalSAPNote,
SUM(CASE WHEN honk = 1 THEN 1 ELSE NULL END) AS TotalHonks,
dbo.Employee.emp_user_id
FROM
dbo.safety_obs_data
INNER JOIN dbo.Employee ON dbo.safety_obs_data.create_by_emp_no = dbo.Employee.emp_no
WHERE
(dbo.safety_obs_data.create_dte BETWEEN CONVERT(DATETIME, @start, 102) AND CONVERT(DATETIME, @end, 102))
GROUP BY dbo.Employee.emp_user_id

View 8 Replies View Related

Divide By Zero

Jun 5, 2008

SELECT CASE WHEN (SUM(CASE WHEN Rspec_Vulgar = 'Y' THEN 1 ELSE 0 END) + SUM(CASE WHEN Rspec_Vulgar = 'N' THEN 1 ELSE 0 END))
= 0 THEN '0' ELSE (SUM(CASE WHEN Rspec_Vulgar = 'Y' THEN 1 ELSE 0 END) * 1.0) / (SUM(CASE WHEN Rspec_Vulgar = 'Y' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN Rspec_Rude = 'Y' THEN 1 ELSE 0 END)) END AS Rspec_Vulgar
FROM dbo.TekliveQuery

---
Note:
How can I avoid the the error message if the dividend and the divisor are both 0?

View 5 Replies View Related

Divide By Zero

Mar 8, 2006

When I specify a formula between Computed Column Specification, I have twozero values, getting Divide by Zero error, any idea how can I avoid this? Istill want SQL Server to display Zero if it is 0/0, is this possible in SQLServer database?ThanksJ.

View 3 Replies View Related

Divide By Zero

Feb 12, 2007

Hi,

In the BI developement, in a matrix i'm trying to avoid division by zero, but even if i test the field before the division, i've got the error everytime.

I put the folowing test condition in the field, but i've got an error.

Ex : iif(Turnover <> 0, Cost/Turnover,0)

But i've got error message when the turnover is 0.

Thanks for your help.

View 3 Replies View Related

Sql Preventing Divide By Zero

Jul 4, 2007

  1 ALTER PROCEDURE links_GetAllLinks
2 @startRowIndex INT,
3 @maximumRows INT,
4 @sortExpression nvarchar(50)
5 AS
6
7
8
9
10
11 SET @startRowIndex = @startRowIndex + 1
12 --SELECT @TopicsFrom = CASE @TopicsDays WHEN '1' THEN DATEADD(day,-1,getdate()) WHEN '2' THEN DATEADD(day,-7,getdate()) WHEN '3' THEN DATEADD(day,-14,getdate()) WHEN '4' THEN DATEADD(month,-1,getdate()) WHEN '5' THEN DATEADD(month,-3,getdate()) WHEN '6' THEN DATEADD(month,-6,getdate()) WHEN '7' THEN DATEADD(year,-1,getdate()) ELSE DATEADD(year,-1,getdate()) END
13 -- populate the table CAST(getdate() as int)
14
15
16 IF @sortExpression LIKE ''
17 BEGIN
18 SET @sortExpression = 'links_Links.link_date'
19 END
20 DECLARE @sql nvarchar(4000)
21 SET @sql = 'Declare @Links TABLE
22 (RowNumber INT,
23 link_id INT,
24 cat_id INT,
25 cat_title VARCHAR(100),
26 sub_id INT,
27 sub_name VARCHAR(100),
28 link_aproved BIT,
29 link_name VARCHAR(100),
30 link_url varchar(100),
31 link_desc varchar(500),
32 link_date datetime,
33 link_rating INT,
34 link_ratingscount INT,
35 link_ratingvalue INT,
36 link_poster uniqueidentifier,
37 link_comments INT,
38 hit_date datetime);INSERT INTO @Links
39 SELECT ROW_NUMBER() OVER (ORDER BY ' + @sortExpression + '), links_Links.link_id, links_Links.cat_id, links_Categories.cat_title, links_Links.sub_id, links_SubCategories.sub_name, links_Links.link_aproved, links_Links.link_name, links_Links.link_url, links_Links.link_desc, links_Links.link_date, links_Links.link_rating, links_Links.link_ratingscount, (links_Links.link_rating/links_Links.link_ratingscount) as link_ratingvalue, links_Links.link_poster, links_Links.link_comments, links_Links.hit_date
40 FROM links_Links INNER JOIN
41 links_Categories ON links_Categories.cat_id = links_Links.cat_id INNER JOIN
42 links_SubCategories ON links_SubCategories.sub_id = links_Links.sub_id
43 WHERE links_Links.link_aproved = 1;SELECT * from @Links
44 WHERE RowNumber BETWEEN ' + CONVERT(nvarchar(10), @startRowIndex) + ' AND (' + CONVERT(nvarchar(10), @startRowIndex) + ' + ' + CONVERT(nvarchar(10), @maximumRows) + ') - 1'
45
46
47
48 EXEC sp_executesql @sql
49
50
51 RETURN at row 39, i define a field by dividing to values. I use these for ratings (finding the mean). The problem is, when a new link is submited, it has no ratings, so it performs a divide by zero. how do I check if the column "link_ratingscount" is zero? if it is, then return a zero, and if it is not zero, then do the divide?   

View 4 Replies View Related

SQL Divide By Zero Problem

Mar 31, 2006

Hi all,
 
I am having a terrible time with a stored procedure.  I think it has something to do with a divide by zero issue.  Here is my sproc:
 
ALTER PROCEDURE [dbo].[GetPlayers]
@TeamID int
AS
SELECT PlayerID,
TeamID,
FirstName,
LastName,
FirstName + ' ' + LastName As Name,
"SPct" =
CASE (SELECT Count(PlayerID) FROM GameDetail WHERE AtBatID IN(1, 2, 3, 4) AND GameDetail.PlayerID = Player.PlayerID)
WHEN 0 THEN 0
ELSE
Cast
( Cast
( (
(SELECT Count(PlayerID) FROM GameDetail WHERE GameDetail.PlayerID = Player.PlayerID AND AtBatID = '1') +
(SELECT Count(PlayerID) FROM GameDetail WHERE GameDetail.PlayerID = Player.PlayerID AND AtBatID = '2') +
(SELECT Count(PlayerID) FROM GameDetail WHERE GameDetail.PlayerID = Player.PlayerID AND AtBatID = '3') +
(SELECT Count(PlayerID) FROM GameDetail WHERE GameDetail.PlayerID = Player.PlayerID AND AtBatID = '4')
/
(SELECT Count(PlayerID) FROM GameDetail WHERE AtBatID IN(1, 2, 3, 4) AND GameDetail.PlayerID = Player.PlayerID
) * 1.0
) As int
) As Decimal(4,3))
End
FROM Player
WHERE TeamID = @TeamID
ORDER BY FirstName, LastName
 
Here is the error I get when I run this:
Msg 8115, Level 16, State 8, Procedure GetPlayers, Line 9
Arithmetic overflow error converting int to data type numeric.
So the results should look like: .333 or .500 or .000
 
It's driving me crazy.  I have tried everything but cannot get the desired results.  I'm hoping someone can help me.
 
Thanks,
Bob
 
 

View 3 Replies View Related

Supressing Divide By Zero

Oct 19, 2004

I know you can resolve "divide by zero" messages with a CASE statement.

However, the T-SQL docs suggest that I should be able to simply turn off both the error message and the effect of the error with
SET ARITHIGNORE ON
and
SET ARITHABORT OFF

I am trying to execute these two statements within a stored proc but I need their effect to reach to a select statment that is a sql string (as in 'EXECUTE (@SQLSTRING)' within the same stored proc.

Am I wrong to expect these statements to be able to deal with "divide by zeroes"?

I haven't been able to make it work so I would appreciate any pointers that someone might have.

Many thanks.

View 2 Replies View Related

How To Set Decimal After Divide

Nov 23, 2006

let say
1/2 = 0.5
anyone know how to set it become 0.5? by default the value will become 0,

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved