SQL Trigger On Different Tables - sql

I have a Database that looks like this.
Whenever a new user is created, the Id of the User(UserName) needs to be stored in the Budget table. After this, I want the attribute category in the Budget table to be filled with every category in the Category table.
My current Category table:
As you can see, I currently have 3 categories. Is it possible to create a Trigger which loops trough the categories, and inserts the Category.Id into Budget.Category.
The Budget table should look like this after a user has been created:
I don't know how to add each categoryId to the Budget table.

To insert the values into the budget table, the code would look something like this:
insert into budget(UserId, CategoryId, Date, Value)
select new.userid, c.categoryId, current date, 0
from categories c;
No foreach is required, but the syntax varies by database. In particular:
The syntax for the current date.
The syntax for accessing the values being inserted.

Related

How do I create a table the same time as other tables that pulls totals from each?

For class I'm creating a database that keeps track of my finances. I have a table for each type of item I purchase. For example Rent, Food, Hygiene, Entertainment,etc... I also have a table called Register that I want to display the monthly total for each item. The column names for the totals in the tables are as follows: MonthlyRentTotal, MonthlyFoodTotal, etc...
I want the Register table to pull the total from each Table so I don't have to enter them twice. Any Ideas on how I can do that? I don't want to create a view either. I want it to be an actual table. I'm not even sure if this is possible.
I assume that Rent, Food, Hygiene, Entertainment have same column type.
INSERT INTO Register
SELECT *
FROM
(SELECT SUM(a.rent_value) AS value,
'monthlyrent' AS TYPE
FROM Rent a
UNION SELECT SUM(b.food_value) AS value,
'monthlyfood' AS TYPE
FROM Food b) d pivot(max(value)
FOR TYPE IN (monthlyrent, monthlyfood)) piv;
Data was pivoted in order to be inserted into Register table.
You can put this query in a stored procedure or simply run it manually. If you want to have updated data in the Register table I suggest to :
Create a stored procedure using a TRUNCATE for Register table followed by the above query
Create an SQL Job and schedule the run of the stored procedure anytime you need.
Hope this helps. Let me know if you need additional details.
You should only separate the items into separate tables if there is a compelling reason. For the items you describe, I see no compelling reason.
I would imagine a data structure like this:
itemCategories -- contains the list of categories you care about, such as "food", "hygiene", and so on.
Purchases -- contains each purchase, with columns like purchaseDate, location, itemCategory, description, and so on.
You may want additional tables for other entities, such as "location".
What you are calling a Register table would then simply be a query or view on Purchases.

SQL Server : Insert into Multiple Tables with Foreign Keys

I'm working on a project tracking grocery expenses. I have the following tables with predefined values already inserted:
Store (where we bought the food)
Shopper (me or my wife)
Category (of food)
I also have tables that are awaiting input.
They are:
Receipt (one shopping trip with multiple food items)
Food (each food item)
FoodReceipt (bridge table between Receipt and Food)
I have my constraints set up the way I need them, but I am at a bit of a loss when it comes to writing an INSERT statement that would allow me to insert a new record that references values in the other tables. Any thoughts would be greatly appreciated.
Thanks!
SCOPE_IDENTITY will give you the single value of the last identity. While it may well work in this case, that isn't necessarily the best approach in the general case when you want to insert in sets.
I'd consider using the OUTPUT clause to output the inserted items ID into a temp table, then you can join them back to the subsequent inserts.
`INSERT INTO... OUTPUT INSERTED.ID INTO tempIDs
INSERT INTO other_table inner join tempIDs ...`
Wrap it up in a SP.
https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-2017
Using the final three tables as an example, insert into the reciept table and use the ScopeIdentity() function to get the id (you have to use an identity column as the primary key). Repeat the following for each food item - insert into the food table, use ScopeIdentity to get the primary key and then insert a row into FoodReceipt the saved value for the receipt and the saved value for the current food row.

Moving specific data from one database to another

This is for SQL Server. I have tables Product (product_id pk) and Customers (cust_id pk). And a few other tables that have the above as foreign key.
I need to come up with a good set of INSERT statements that can move rows from the tables above, for a specific Product from one database to another. Is there a good tool that can do this?
The twist is also that the different databases have different ids for products and customers - so inserts should first look up the ids based on something else like product name and customer name (assuming there are no duplicates).
If the databases are within the same server, you may use the following assuming they have the same table structure
USE [TESTDB]
SELECT *
INTO #values
FROM producttbl
USE [OTHERDB]
INSERT INTO tbl_product
SELECT *
FROM #values
The twist is also that the different databases have different ids for
products and customers - so inserts should first look up the ids based
on something else like product name and customer name (assuming there
are no duplicates).
For this, you have to create an SQL statement with conditions to lookup for those specific records

User inventory stacking SQL Server 2014

I want to stack items in users their inventory.
If you have a new weapon with the same ItemID, it just creates a new row like in the picture below.
If the ItemID exists then it needs to change the quantity to the number of weapons you've actually got, and delete the duplicate rows.
What type of query is that, or help me on the way?
There are various problems in your table design. First, I do not understand the purpose of InventoryID here. Because the InventoryID is unique (which I would assume to be the primary key, that's why every time when you have an additional itemID (same or not), it will be treated as a new row.
I do not know what you're trying to achieve in the end, but,
Option 1: Create a separate table Inventory with InventoryID and probably ItemID and LeasedUntil, then modify your current table to only CustomerID and ItemID and quantity
Option 2: keep your current table, add another table called Item that has only ItemID and Quantity
You may also want to review table Normalization here: http://support.microsoft.com/kb/283878
Your current table is in 1NF

Advanced SQL Update query

I'm trying to create a sql update query for a stored procedure but I'm getting lost in trying to figure out how to to do it.
Here is what I'm trying do:
The table I'm wanting to update has 3 columns: product_item_id, rel_product_item_id, and sequence. This table is called "ProductRelationship".
I also have another table called ProductDetails. This table also contains a column called product_item_id as well as a column called "sku".
I want the user to be able input the sku number that updates the rel_product_item_id column with the corresponding product_item_id number from the ProductDetails table.
So on the front-end, the user is inputting a sku, but in the backend, the product_item_id number is getting updated in the database based on the sku the user entered.
Basically its cross-referencing the sku number on the details table, finding the appropiate product item id number and inserting that id number in the table instead of the user-inputted sku number.
update ProductRelationship
set rel_product_item_id = (select product_item_id
from ProductDetails
where sku = #UserInput)
where product_item_id = #ValueSetOnPage