SQL Trigger - Allocation Amount - sql-server

i need to create a complex trigger in my database.
I try to explain my problem:
In my database I have 3 tables: Cash table, invoice table and installment payment table. Now I need to create a trigger. When I enter a payment in the collection table, the trigger should divide the amount entered by covering the uncovered amounts of the invoices (invoice table) starting from the oldest invoice due date. Furthermore, if installment payments are envisaged, I would need to divide the amount also on any installments starting from the oldest installment due date.
like this function: https://andrewtuerk.wordpress.com/2013/01/17/splitting-allocations-across-multiple-records-in-a-single-statement/
or this: SQL Server Allocation of amount in bill
How can I activate a trigger when I insert row in table?
Many thanks,
Andrea.

Related

Create a Table based on results of a column of data in another worksheet and eliminate null values

To set this up....I have roughly 12,000 rows of data that captures sales detail activity. I have an Excel function in a column to the right of the data that identifies the invoice number based on unique qualifiers (if the transcation meets the qualifier it lists the invoice number and, if not, assigns ""). Of the 12,000 rows of data maybe 50 will qualify. I then need to use the invoice numbers that qualify to pull sales and COGS data for all those invoices that match the qualifying invoice numbers (another explanation is necessary at this point....an invoice that qualifies will be listed twice....once that contains the information that identifies whetehr it qualifies but that row will have no sales data and a second time with thye dsales data...I do not know why it does it this way. So, in other words, the row of data with the sales information I need to capture does not contain the data that allows me to recognize that an invoice qualifies). Each mopnth adds the current month's sales data to the population...so, 12,000 rows this month and it will be 16,000 next month and so on.
I was hoping to create a table that pulls only the qualifuying invoice numbers from the sales data (it would basically create a table of 50 (in my example) while ignoring the 11,950 rows where the cell equals ""). I can do a simple pivot table but next month I need it to recognize the new population of data and update based on the additional rows of new monthly data as well as the rows of data from prior months.
Any soultions/ideas are much appreciated!

MS SQL Server, arrays, looping, and inserting qualified data into a table

I've searched around for answer and I'm not sure how best to frame the question since I'm rather new to SQL Server.
Here's what I got going on: I get a weekly report detailing the products that have been sold and the quantity of each. This data needs to go into a yearly totals table. In this table the first column is the product_id and the next 52 columns are week numbers, 1-52.
There's a JOIN that runs on the product_id of both the weekly and yearly tables. That finds the proper row and column to put the weekly quantity data for that product.
Here's where I'm not sure what to do. In 2019 there are no product_id in that column. So there's nothing to JOIN on. Those product_id need to be added weekly if they aren't there. I need to take the weekly report of product_id and quantity and check each product_id to see if it's in the yearly table. If not I need to add it.
If I had it my way I'd create an array of the product_id numbers from the weekly data and loop through each one creating a new record in the yearly table for any product_id that is not already there. I don't know how best to do that in SSMS.
I've searched around and have found different strategies for this. Nothing strikes me as being a perfect solution. There's creating a #temp table variable, a UNION using exclude to get just those that aren't in the table, and a WHILE loop. Any suggestions would be helpful.
I ended up using a MERGE to solve this. I create a table WeeklyParts to dump the weekly data into. Then I do a MERGE with the yearly table inserting only those where the is no match. Works well.
-- Merge the PartNo's so that only unique ones are added to the yearly table
MERGE INTO dbo.WeeklySales2018
USING dbo.WeeklyParts
ON (dbo.WeeklySales2018.PartNo = dbo.WeeklyParts.PartNo)
WHEN NOT MATCHED THEN
INSERT (PartNo) VALUES (dbo.WeeklyParts.PartNo);

SQL Server Database Design - Seperate Table for Sale and Purchase

I am building a new business application for my personal business which has close to ~100 transactions of sale and purchase per day. I am thinking of having Separate tables to record the sale and purchase with another linked table for Items that were sold and a seperate linked table with items that were purchased.
Example:
**SaleTable**
InvoiceNo
TotalAmt
**SaleTableDetail**
LinkedInvNo
ProductID
Quantity
Amount
etc.,
would this design be better or would it be more efficient to have one transactiontable with a column stating sale or purchase?
-From an App/Database/Query/Reporting Perspective
An invoice is not the same as a sales order. An invoice is a request for payment. A sales order is an agreement to sell products to a party at a price on a date.
A sales order is almost exactly the same as a purchase order, except you are the customer, and a sales order line item can reference a purchase order line item. You can put them in separate tables, but you should probably use Table Inheritance (CTI, extending from an abstract Order). Putting them in the same table with a "type" column is called Single Table Inheritance and is nice and simple.
Don't store totals in your operational db. You can put them in your analytic db though (warehouse).
You are starting small, thats a quick way to do. But, I am sure, very shortly you will run into differences between sale and purchase transactions, some fields will describe only a sale and some fields that will be applicable only for purchases.
In due course, you may want to keep track of modifications or a modification audit. Then you start having multiple rows for the same transaction with fields indicating obsoletion or you have to move history records to another table.
Also, consider the code-style-overhead in all your queries, you got to mention the Transaction Type as sale or purchase for simple queries.
It would be better to design your database with a model that maps business reality closest. At the highest level, everything may abstract to a "transaction", with date, amount and some kind of tag to indicate amount is paid or received against what context. That shouldn't mean we can have a table with Tag, Date, Amount, PayOrReceive to handle all the diverse transactions.

banking database design issue

I'm trying to build a database for banking I created a table for every account loan, deposit , checking account and also for payment methods checks, debit cards and cash.
My question is that how should I handle transactions between the tables knowing that the transactions are possible between all the tables?
For example customer can withdraw money using debit card, transfer money from checking account to loan or deposit money to checking using a check.
My first solution is to create one transaction table for all the transactions and the Cardinality (0...1 n ) so that only one type of payment and one account, so should I go with it or just create a transaction table for every relationship between two tables?
If "I created a table for every account, loan, deposit , checking account" means that you have more than four tables then you are doing something very very wrong. You should have one table for customers and one table for transactions. A transaction is money moving from one account to another account, so a simple transaction table would have the fields id, transaction date, credit account, debit account, amount. In accountancy, there are frequently transactions which involve several credit and debit accounts so these can't be maintained in the simple transaction scheme outlined above.
If you want to represent loans, then you'll probably need two more tables: one table contains the atomic details of all the loans (date given, account of the loanee, total amount, nominal interest rate, etc) and the other table contains the projected repayments of each loan.
There is no need for further tables representing deposits or checking accounts: these can be represented as accounts, with a type field designating which kind they are.

Saving data in database for Monopoly game

Let's say I have an app (a Monopoly game) with many users, where each user has a balance, and they make transactions between them.
I have a table with all the users (userID, name, email) and a table with all the transactions and the users who made them (user1, user 2, amount).
Now if I need to present a balance for each user, would it be better to keep the balance for each user in the users table and update it every time a transaction is made, or should I calculate it from the transactions table every time I wont to present it? Assume this game will have a lot of traffic, so what is a more reasonable approach for 10,000+ users and about 120,000+ transactions per week?
Having a new column balance in the user table is a redundancy beacause the value could be calculated with a query on the transactions table.
However one of the DB design process is the estimation of how many read and writes could happen on a particular table. If this estimation is high it's logic and permitted to simplify the result of some read or write and have a redundancy on the DB to afford the many reads requested by the web pages and display values with less processing time.
In your case the balance column update could be done with a trigger on the transactions table that calculate the balance for the two users involed.

Resources