-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_database.sql
72 lines (65 loc) · 1.64 KB
/
create_database.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
-- Create a PersonalExpenses database
CREATE DATABASE PersonalExpenses;
GO
-- Using the created database
USE PersonalExpenses;
GO
-- Creating the Categories table
CREATE TABLE Categories (
Id INT PRIMARY KEY IDENTITY(1,1),
Name NVARCHAR(255) NOT NULL
);
GO
-- Create Expenses table
CREATE TABLE Expenses (
Id INT PRIMARY KEY IDENTITY(1,1),
CategoryId INT,
Amount DECIMAL(18,2) NOT NULL,
Date DATE NOT NULL,
Description NVARCHAR(MAX),
CONSTRAINT FK_Expenses_Categories FOREIGN KEY (CategoryId) REFERENCES Categories(Id)
);
GO
-- Inserting initial data into the Categories table
INSERT INTO Categories(Name)
VALUES
('Clothing'),
('Debt Repayment'),
('Dining Out'),
('Education'),
('Entertainment'),
('Gifts & Donations'),
('Groceries'),
('Health'),
('Household Supplies'),
('Insurance'),
('Investments'),
('Other'),
('Personal Care'),
('Rent'),
('Savings'),
('Subscriptions'),
('Transportation'),
('Travel'),
('Utilities');
GO
-- Adding a CategoryId column to the Expenses table if it doesn't already exist
IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Expenses' AND COLUMN_NAME = 'CategoryId')
BEGIN
ALTER TABLE Expenses
ADD CategoryId INT;
END
GO
-- Update CategoryId based on existing data in Category
UPDATE Expenses
SET CategoryId = c.Id
FROM Expenses e
JOIN Categories c ON e.CategoryId = c.Id;
GO
-- Removing the Category column from the Expenses table if it is not already removed
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Expenses' AND COLUMN_NAME = 'Category')
BEGIN
ALTER TABLE Expenses
DROP COLUMN Category;
END
GO