I’m trying to do what seems like a basic cast of int to decimal, and it’s not working. I’ve experimented with performing the cast before the insert, no better. I want to use the decimal values to show percentage change. The code is below, along with output. Any help would be great..
DECLARE @tblVar TABLE (LatestCount INT, PriorCount INT,
PctChgLatestVsPrior DECIMAL, PctChgLatestVsAvg DECIMAL)
DECLARE @tbl CHAR(30)
DECLARE @dte DATE
DECLARE @dte2 DATE
DECLARE @latestCount INT
DECLARE @priorCount INT
DECLARE @avgAllCounts INT
SET @tbl = 'tblDailyPricingAndVol'
SET @dte = '5/8/12'
SET @dte2 = '5/7/12'
EXEC spAvgOfCountByDateAddedByTable @tbl, @avg = @avgAllCounts OUTPUT
EXEC spCountOfDateAddedByTableAndDate @tbl, @dte, @count = @latestCount OUTPUT
EXEC spCountOfDateAddedByTableAndDate @tbl, @dte2, @count = @priorCount OUTPUT
INSERT INTO @tblVar
VALUES (@latestCount, @priorCount,
CAST((@latestCount-@priorCount) AS DECIMAL)/CAST(@priorCount AS DECIMAL),
CAST((@latestCount-@avgAllCounts) AS DECIMAL)/CAST(@avgAllCounts AS DECIMAL))
SELECT * FROM @tblVar
Output:
19548
7107
8483
LatestCount PriorCount PctChgLatestVsPrior PctChgLatestVsAvg
7107 8483 0 -1
You need to give decimal scale/precision
See here: Decimal and Numeric problems when you don’t specify precision and scale
Some examples: DECIMAL(30,10) or DECIMAL(20)
See more in Books On Line http://msdn.microsoft.com/en-us/library/ms187746.aspx