/*
Stored Procedure
April 30, 2021
Mohamad Chaker
*/
USE CIS111_BookStoreMC
GO
--drop the procedure
IF OBJECT_ID('spAssetInfo') IS NOT NULL
DROP PROC spAssetInfo
GO
--Create the stored procedure
CREATE PROC spAssetInfo
AS
--Create a temporary table to display the inventory
SELECT AssetID, Description, Cost, PurchaseDate
INTO #temptable
FROM Assets
--Add a new column to the temporary table displaying the date an asset is completely depreciated
ALTER TABLE #temptable ADD CurrentValue MONEY
DECLARE @years INT;
DECLARE @currentYear INT;
SET @currentYear = YEAR(getdate());
DECLARE @cost MONEY;
--Add a new column to the temporary table to display the current value of the item in the current year
ALTER TABLE #temptable ADD CompleteDepreciationYear DATE
--@value holds the cost of an asset and is used to check when the value of an asset drops low
DECLARE @value MONEY;
SET @value = 0.00;
--@counter is an int that I used to iterate over the table rows
DECLARE @counter INT;
--@depreciationNum holds the amount of years until an item is completely depreciated to be later used in DATEADD()
DECLARE @depreciationNum INT;
SET @counter = 1;
DECLARE @assetsTableSize INT;
SET @assetsTableSize = (SELECT COUNT(*) FROM Assets);
WHILE (@counter <= @assetsTableSize)
BEGIN
--Current Value
SET @years = @currentYear - (select YEAR(PurchaseDate) From Assets Where AssetID = @counter);
SET @cost = (select Cost From Assets Where AssetID = @counter);
--calculate current value of each asset
WHILE(@years>0)
BEGIN
SET @cost = @cost * 0.8;
SET @years = @years - 1;
END
--add the current value of each asset to the temporary table
UPDATE #temptable
SET CurrentValue = @cost
WHERE AssetID = @counter;
--Deprection Year
SET @depreciationNum = 0;
SET @value = (select Cost From Assets Where AssetID = @counter);
WHILE(@value >0.1)
BEGIN
SET @value = @value * 0.8;
SET @depreciationNum = @depreciationNum + 1;
END
--add the date each asset is completely depreciated to the temporary table
UPDATE #temptable
SET CompleteDepreciationYear = CAST(DATEADD(year, @depreciationNum, (select PurchaseDate From Assets Where AssetID = @counter)) AS DATE)
WHERE AssetID = @counter;
--increment the counter
SET @counter = @counter + 1;
END
--display the assets inventory
SELECT * FROM #temptable
提示:显示资产库存以及当前价值(每年减去 20% 的折旧)。还显示每个项目将完全折旧的年份。
基本上,我试图显示带有 PurchaseDate 的资产库存以及项目完全折旧的日期,资产每年折旧 20%。我尝试创建一个临时表并将一些资产表列复制到其中,然后为资产完全折旧的日期添加一列。
我使用迭代解决方案实现了这一点,但建议我在 SO 上发布以尝试使用基于集合的实现来执行此操作。我是 SQL 的新手,并且新了解到它是一种基于集合的语言,并且它不太适合迭代解决方案。
先感谢您!