How to deduct quantity of items in database? - vb.net

I'm creating a system where I must deduct and add by one if the item is borrowed/returned. In my system I have 2 tables:
tblItems(_itemnumber_, _itemname_, _quantity_)
tblBorrow(_dateborrowed_, _datedue_, _status_)
Where if I borrowed an item the status will be borrowed and the quantity will deducted by 1 and if the status is returned the quantity will added by 1. This is my idea(I already how to add and update) but i don`t know how to code this idea. I'd really appreciate your help.
I`m using imports system.data.oledb

First, the underscores might be eliminated to improve readability.
Next, tblBorrow needs itemnumber, else all Borrowings look the same.
tblBorrow(_itemnumber_,_dateborrowed_, _datedue_, _status_)
Then the Borrow_Clicked button would have code to the effect of
If tblItems for this _itemnumber_ has _quantity_ <= 0 then
msg"There is no Quantity to Borrow"
exit
else
Update tblItems Set _quantity_ = _quantity_ - 1 Where _itemnumber_ = x
Insert tblBorrow Item#, Date, Due, "Borrowed"
End If
There would also be a Returned_Click button, with code to the effect of
If tblBorrow for this Item# exists with a "Borrowed" status then
Update tblItems Set _quantity_ = _quantity_ + 1 Where _itemnumber_ = x
Update tblBorrow Set Status = "Returned"
else
msg"Item status is not Borrowed"
End If
Each of these should also edit the Item# to insure that is it valid.

Related

Compare data in the same table

I have a table that stores monthly data and I would like to create a comparison between the quantity movement within a period.
Here is an example of the table
.
The SQL statement below is meant to return any changes that has happened within a period - any fund/policy partial or total loss as well as partial or total gain. I have been battling with it for a while - any help would be well appreciated.
I currently have 5 sets of unions - (where the policies and funds match and there's a difference in quantities held, where the policies exist in the previous and not in the current and vice versa and where the securities exist in the previous and not in the current and vice versa) but the other unions work save for the last couple (where the securities exist in the previous and not in the current and vice versa). It doesn't seem to return every occurrence.
SELECT distinct pc.[Client]
,pc.Policy
,cast(pc.Qty as decimal) AS CurrQ
,0 AS PrevQ
,cast(pc.Qty as decimal) - 0 AS QtyDiff
,CASE WHEN cast(pc.Qty as decimal) - 0 > 0 THEN 'Bought Units'
WHEN cast(pc.Qty as decimal) - 0 < 0 THEN 'Sold Units'
ELSE 'Unknown'
END AS TransactionType
,convert(varchar,cast(pc.[ValDate] as date),103) AS CurrValDate
,'' AS PrevValDate
FROM table pc
WHERE convert(varchar,cast(pc.[ValDate] as date),103) = convert(varchar,getdate(),103)
AND pc.Policy IN (SELECT policy
FROM table
WHERE convert(varchar(10),[ValDate],103) = convert(varchar(10),getdate()-1,103)
AND pc.[Fund] NOT IN (SELECT PM.[Fund]
FROM table pc
LEFT JOIN table pm ON pc.policy = pm.policy
WHERE convert(varchar,cast(pc.[ValDate] as date),103) = convert(varchar,getdate(),103))
AND convert(varchar,cast(pm.[ValDate] as date),103) = convert(varchar,getdate()-1,103))
As #Larnu rightly mentioned in the comment section, the extra conditions in the query changed the run from a LEFT JOIN to an INNER JOIN. I changed the code to have policy, fund and date in the ON clause:
FROM table pc
LEFT JOIN table pm ON (pc.policy = pm.policy
AND pc.fund = pm.fund
AND pc.[ValDate]-1 = pm.[ValDate])
and got rid of the sub queries.
Thanks again Larnu.

Populate rows based on another row ( Copy Prices from branch 0, to all other branches)

I am trying to populate rows based on another row,
For example
Update the Product Price table where branchID = 0
to all other products where the branchid <> 0 based on each product code
In the table there is
7 rows of the same product, each row is meant to be identical, but the only difference is the branchid
I want all data from branch 0 row to populate the rest for the product
my current update script does run, but it uses up so much space on the transaction log that it fails, and it takes 2 hours to run
UPDATE ProductPrice
SET StandardSell = pp2.StandardSell,
StandardBuy = pp2.StandardBuy,
InternalCost = pp2.InternalCost,
BuyPerID = pp2.BuyPerID,
AverageCostPerID = pp2.AverageCostPerID,
InternalCostPerID = pp2.InternalCostPerID,
SellPerID = pp2.SellPerID
FROM (SELECT BranchID, ProductID, StandardSell, StandardBuy,SellPerID, InternalCost,BuyPerID,AverageCostPerID,InternalCostPerID
FROM ProductPrice
WHERE BranchID = 0
) AS pp2 INNER JOIN
ProductPrice AS pp1
on pp1.ProductID = pp2.ProductID
WHERE pp1.ProductID = pp2.ProductID
I want products to be updated with the prices from branch 0 to all other branches per product.
This is too long for a comment.
The first observation is that you should fix your data model. Repeating the same columns on seven records is evidence that your data is not normalized. The seven columns that you want to update should probably be in the ProductPrice table.
Then you want a ProductBranch table, with additional columns and the branch id.
That said, if you are stuck with the data model, you are stuck with an update that basically updates all rows. Instead, create a new table with all the columns you want:
insert into temp_productprice
select . . .
from . . .;
Then truncate productprice and insert the new data into it. A bulk insert is more efficient than a giant update.
Finally, you could also try using window functions:
with toupdate as (
select pp.*,
max(case when branchid = 0 then StandardSell end) as StandardSell_0,
max(case when branchid = 0 then StandardBuy end) as StandardBuy_0,
from productprice pp
. . .
)
update toupdate
set StandardSell = StandardSell_0,
StandardBuy = StandardBuy_0,
. . .
from branchid <> 0;
Thank you for your suggestions,
In the end I just gave the log file more space. Then let it run- it takes 2 hours though lol.
But its done
Thanks the script i posted works for anyone elses use.

SQL Server - WHERE inside CASE?

I'm fairly new to SQL Server and I'm having trouble implementing a WHERE statement inside a CASE, specifically for a trigger I'm working on.
I have 2 tables with the following fields:
Receipt(ItemID,Quantity)
and
Warehouses(WarehouseID,Stock)
|WarehouseID|Stock|
-------------------
|ARM01 |100 |
|ARM02 |100 |
The trigger checks whether a row with a specific quantity of any given item was inserted, altered or removed to Receipt and then subtracts or adds to the Stock of the Warehouses table.
So if I add a row with 200 Quantity in Receipt, it will subtract 100 from the Stock of WarehouseID 'ARM01', and if there is no Stock left in 'ARM01' (which there isn't because there is only 100), it will subtract the other 100 from 'ARM02'. Of course if 'ARM02' has a Stock of 0 it will print an error but I'll worry about that later.
The thing is, SQL Server doesn't accept a WHERE inside a CASE, because, of course, the entire CASE is already part of the SET statement and WHEREs only come after a SET. It's weird but I couldn't find an answer online yet for such a simple thing.
My goal:
CASE 1
UPDATE 'Stock of Table' where 'WarehouseID of Same Table' = 'ARM01'
CASE 2
UPDATE 'Stock of Table' where 'WarehouseID of Same Table' = 'ARM02'
I also realize the calculus for Stock -/+ Quantity and vice-versa might be wrong right now and I also have 2 statements in parenthesis after a THEN, separated by a AND because I was trying to distribute the first 100 to ARM01 and the rest to ARM02. That's probably very, very misguided and apologies for the incorrect code but for now I just want to figure out where to use a WHERE statement.
CREATE TRIGGER SubtractStock ON Receipt
FOR INSERT, UPDATE, DELETE
AS
[snipped UPDATE for deleted because it only exchanges '+' for '-' in the operation]
UPDATE Warehouses
SET Stock =
(CASE
WHEN inserted.Quantity <= Stock THEN Stock - Quantity WHERE WarehouseID = 'ARM01'
WHEN inserted.Quantity > Stock THEN (Stock - Quantity WHERE WarehouseID = 'ARM01')
AND (Quantity - Stock WHERE WarehouseID = 'ARM02')
END)
FROM inserted JOIN Warehouses ON inserted.ItemID = Warehouses.ItemID
Thank you!
I hate triggers, and this is a bad idea for one. With that out of the way.
For ARM01, move the WHERE to the WHEN with an AND:
SET Stock =
(CASE
WHEN inserted.Quantity <= Stock AND WarehouseID = 'ARM01'
THEN Stock - Quantity
...
The next problem is you need to see two rows to set the stock for ARM02, what the stock is in ARM02 to see if you need to subtract from ARM02, and the stock in ARM02 to subtract from. So moving the condition in the where somewhere else won't help. Probably two update statements, update ARM01, with an output clause to temp table or table valued variable to give before stock values for ARM01, then use that to update the values for ARM02.
Again, this sort of complicated logic rarely is appropriate inside a trigger.
Please try like this...Use proper aliases..
CREATE TRIGGER SubtractStock ON Receipt
FOR INSERT, UPDATE, DELETE
AS
UPDATE W
SET Stock = CASE
WHEN WarehouseID = 'ARM01' AND I.Quantity <= Stock THEN Stock - Quantity
WHEN WarehouseID = 'ARM01' AND I.Quantity > Stock THEN Stock - Quantity
WHEN WarehouseID = 'ARM02' THEN I.Quantity - Stock
END
FROM inserted I JOIN Warehouses W ON I.ItemID = W.ItemID

SQL Noob compare table in opencart

I have one table called VEGAN with model numbers that i want 3800 rows with model or SKU codes. thats it.
In the main oc_products table there are 15000 products / rows with over 20 columns, In one of those columsn there is a control for enabled which can be set to 0 or 1.
I want to Disable all products in the main oc_products table if they are not in the VEGAN table, or Disable(set status to 0) them all first and Enable them (set status to 1) if they are in the Vegan Table.
So far I have come up with this... I am a first timer here.
FIRST DISABLE EVERYTHING...
UPDATE oc_product
SET status= '0'
WHERE 1
then...
UPDATE oc_product SET status= '1' WHERE 'ocproduct.model' = ‘VEGAN.SKU'
It doesn't work and Im stuck,
please help.
Try this query...
update oc_product set status = 1 where model in (select sku from vegan)
This assumes that oc_product.model matches vegan.sku.
Any vegan.sku with a matching oc_product.model will get oc_product.status set to 1.
For your second update statement you should do something like:
UPDATE oc_product SET status = '1'
WHERE ocproduct.model IN (SELECT SKU FROM Vegan)
or you can use the alternate format:
UPDATE oc_product SET status = '1'
FROM oc_product
INNER JOIN Vegan
ON oc_product.model = Vegan.SKU

SQL error with nested SELECT

The error is 'Operation must use an updatable query'.
I am trying to update the 'orders' table with the information below, however only the price of 1 item will be provided through a text box and I am trying to calculate the total order value using the quantity ordered, which will already be in this table.
The code below includes the data taken from the variables. With the 2 in 'VAT = 2' and 'price = 2' being the price of one single unit (£2.00). The total order value will be stored within the 'price' field and the VAT should be calculated using the same code, but times by 0.2 to give the 20% VAT.
UPDATE orders
SET Invoice_number = 'IN9999',
delivery_note_number = 'DN6000',
price =2 *
(SELECT quantity
FROM orders
WHERE purchase_order_number = 'PO7512'
),
VAT = (2 *
(SELECT quantity
FROM orders
WHERE purchase_order_number = 'PO7512'
)/100) * 20,
shipping = 3
WHERE purchase_order_number = 'PO7512'
Maybe I can't use nested query's this way. I'm not sure, but any help would be appreciated :) Thanks!
Instead of subquerying, you can access the whole record directly in the update, like so:
UPDATE Orders
SET Invoice_number = 'IN9999',
Delivery_note_number = 'DN6000',
Price = 2 * quantity,
VAT = (40 * quantity)/100,
Shipping = 3
WHERE purchase_order_number = 'PO7512'
Note that with fractions it's always better to multiply first and divide later.