Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Gytenbryer
Starting Member
1 Post |
Posted - 2007-10-05 : 12:29:58
|
| Hello people I have a question about t-SQL in SQL server. I'm using the database Northwind for exercising and I have a problem. I want to calculate the stock at this moment from all products. To do this I’m using two tables called: Products (producten in dutch), transactions products in stock (voorraadtransacties in dutch). The fields in this tables are:ProductenProductnaam (name of the product)Id (number of product)Voorraadtransacties[product-id] (number of product linked on Producten.Id)[Type transactie] (type transaction, can be ‘ingekocht’ (bought) or ‘verkocht’ (sold)Hoeveelheid (number of products that are bought or sold)To calculate the stock of product I want to create a function that returns a table with te actual stoch for each product (productname and actual stock)This is the code that I use.if exists (SELECT *FROM sysobjectsWHERE name = 'fn_VoorraadPerProduct'and type = 'FN')DROP FUNCTION fn_VoorraadPerProductgoCREATE FUNCTION fn_VoorraadPerProduct()RETURNS @Retour table(Prnaam varchar(50),Voorraden int - - actual stock)asBEGINDECLARE @Rij int, @aantal intDECLARE @prodnaam varchar(50)DECLARE @hoev intDECLARE @voorraad intDECLARE @type smallintDECLARE cur1 CURSOR forSELECT p.Productnaam, v.[Type transactie], v.HoeveelheidFROM Producten p, Voorraadtransacties vWHERE p.id = v.[Product-id]GROUP BY P.Productnaam, v.[Type transactie], v.HoeveelheidOPEN cur1 SET @rij = 1SET @aantal = @@Cursor_rowsWHILE @rij < @aantal BEGIN FETCH NEXT FROM cur1 INTO @prodnaam, @type, @hoev If @type = 1 set @voorraad = @voorraad + @hoev if @type = 2 set @voorraad = @voorraad - @hoev set @rij = @rij + 1 ENDclose cur1INSERT INTO @RetourSELECT p.Productnaam, @voorraadFROM Producten p, Voorraadtransacties vWHERE p.id = v.[Product-id]returnENDgomy question is how do i get a the calculated stock in a column of the return table???who has the solution. |
|
|
|
|
|
|
|