Retrieve Data from Different Tables (SQL Server) - sql

I have 4 tables in a SQL Server database with following schema:
Attendance
CREATE TABLE [dbo].[Attendance] (
[AttendanceId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[CourseId] UNIQUEIDENTIFIER NOT NULL,
[StudentId] UNIQUEIDENTIFIER NOT NULL,
[SubjectId] UNIQUEIDENTIFIER NOT NULL,
[Semester] INT NOT NULL,
[Month] NVARCHAR (50) NOT NULL,
[Count] INT NOT NULL,
CONSTRAINT [PK_Attendance] PRIMARY KEY NONCLUSTERED ([AttendanceId] ASC),
CONSTRAINT [FK_Attendance_Student] FOREIGN KEY ([StudentId]) REFERENCES [dbo].[Student] ([StudentId]) );
Course
CREATE TABLE [dbo].[Course] (
[CourseId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
CONSTRAINT [PK_Course] PRIMARY KEY NONCLUSTERED ([CourseId] ASC)
);
Student
CREATE TABLE [dbo].[Student] (
[StudentId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[CourseId] UNIQUEIDENTIFIER NOT NULL,
[Name] NVARCHAR (100) NOT NULL,
[RollNo] INT NOT NULL,
[Semester] INT NOT NULL,
CONSTRAINT [PK_Student] PRIMARY KEY NONCLUSTERED ([StudentId] ASC),
CONSTRAINT [FK_Student_Course] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Course] ([CourseId])
);
Subject
CREATE TABLE [dbo].[Subject] (
[SubjectId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[CourseId] UNIQUEIDENTIFIER NOT NULL,
[Name] NVARCHAR (100) NOT NULL,
[Semester] INT NOT NULL,
CONSTRAINT [PK_Subject] PRIMARY KEY NONCLUSTERED ([SubjectId] ASC),
CONSTRAINT [FK_Subject_Course] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Course] ([CourseId])
);
I need to create a attendance report in the following format:
Course Name | Student Name | Subject Name | Semester | Month | Count
Please tell me what SQL Query I need to use and if there's any change in schema required then suggest the same.
I'm looking forward to have your replies.
Thanks,

You need to use a JOIN in your query so that it only returns rows which match a [StudentId] from the Attendance table.
e.g.
SELECT c.CourseName, s.StudentName, u.SubjectName, u.Semester, a.Month, a.Count
FROM Student s
JOIN Attendance a ON s.StudentId = a.StudentId
JOIN Course c ON a.CourseId = c.CourseId
JOIN Subject u ON c.CourseId = u.CourseId
Something along these lines will only return rows which specifically match

Related

How can I add two different features as a foreign key to my SQL Column?

I have a Car table in my Sql Data and every car has own BrandId that declared every Brands in "Brands" table as a foreign key. I'm just wondering what if I want to add two different BrandId together in my one Car>BrandId Column, what would I do? How can it be possible for adding two features as a foreign key in one spesific column?
Here is my Car Tables Code
CREATE TABLE [dbo].[Cars] (
[CarId] INT IDENTITY (1, 1) NOT NULL,
[CarName] VARCHAR (255) NULL,
[ColorId] INT NULL,
[BrandId] INT NULL,
[ModelYear] VARCHAR (255) NULL,
[DailyPrice] DECIMAL (18) NULL,
[Details] VARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([CarId] ASC),
FOREIGN KEY ([ColorId]) REFERENCES [dbo].[Colors] ([ColorId]),
FOREIGN KEY ([BrandId]) REFERENCES [dbo].[Brands] ([BrandId])
);
And here te code of my Brands table;
CREATE TABLE [dbo].[Brands] (
[BrandId] INT IDENTITY (1, 1) NOT NULL,
[BrandName] VARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([BrandId] ASC)
);
You can simply create your table as follows :
CREATE TABLE [dbo].[Cars] (
[CarId] INT IDENTITY (1, 1) NOT NULL,
[CarName] VARCHAR (255) NULL,
[ColorId] INT NULL,
[BrandId1] INT NULL,
[BrandId2] INT NULL,
[ModelYear] VARCHAR (255) NULL,
[DailyPrice] DECIMAL (18) NULL,
[Details] VARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([CarId] ASC),
FOREIGN KEY ([ColorId]) REFERENCES [dbo].[Colors] ([ColorId]),
FOREIGN KEY ([BrandId1]) REFERENCES [dbo].[Brands] ([BrandId]),
FOREIGN KEY ([BrandId2] REFERENCES [dbo].[Brands] ([BrandId])

T-SQL Use a column name as a parameter in a function used as default value

I have this table:
CREATE TABLE [Operating].[SalesDetails] (
[BillId] INT NOT NULL,
[SerialNumber] NVARCHAR (50) NOT NULL,
[Quantity] INT NOT NULL,
[Price] DECIMAL (19, 2) DEFAULT (IT.SalePrice([SerialNumber])) NOT NULL,
[LineTotal] AS ([Quantity]*[Price]),
[Returned] BIT DEFAULT ((0)) NOT NULL,
[Note] NVARCHAR (30) NULL,
CONSTRAINT [PK_Operating_SalesDetails_BillId_SerialNumber]
PRIMARY KEY CLUSTERED ([BillId] ASC, [SerialNumber] ASC),
CONSTRAINT [FK_Operating_SalesDetails_Operating_Sales_BillId]
FOREIGN KEY ([BillId]) REFERENCES [Operating].[Sales] ([BillId]),
CONSTRAINT [FK_Operating_SalesDetails_Operating_PurchasesDetails_SerialNumber]
FOREIGN KEY ([SerialNumber])
REFERENCES [Operating].[PurchasesDetails] ([SerialNumber]),
CONSTRAINT [CK_Operating_SalesDetails_Price_Positive]
CHECK ([Price]>=(0)),
CONSTRAINT [CK_Operating_SalesDetails_Quantity_Positive]
CHECK ([Quantity]>(0))
);
Function:
CREATE FUNCTION [IT].[SalePrice] (#SerialNumber NVARCHAR (50)) RETURNS DECIMAL (19, 2)
AS
BEGIN
DECLARE #SalePrice DECIMAL (19, 2)
SET #SalePrice = (
SELECT [Sale]
FROM [Operating].[PurchasesDetails]
WHERE [SerialNumber] = #SerialNumber
)
RETURN #SalePrice
END
This is the Purchases Details table:
CREATE TABLE [Operating].[PurchasesDetails] (
[BillId] INT NOT NULL,
[ProductId] INT NOT NULL,
[ManufacturerId] INT NOT NULL,
[SerialNumber] NVARCHAR (50) DEFAULT ([IT].[SerialNumber]()) NOT NULL,
[Quantity] INT NOT NULL,
[Purchase] DECIMAL (19, 2) NOT NULL,
[Sale] DECIMAL (19, 2) NOT NULL,
[Returned] BIT DEFAULT ((0)) NOT NULL,
[Note] NVARCHAR (30) NULL,
CONSTRAINT [PK_Operating_PurchasesDetails_SerialNumber]
PRIMARY KEY CLUSTERED ([SerialNumber] ASC),
CONSTRAINT [FK_Operating_PurchasesDetails_Operating_Purchases_BillId]
FOREIGN KEY ([BillId]) REFERENCES [Operating].[Purchases] ([BillId]),
CONSTRAINT [FK_Operating_PurchasesDetails_Operating_Products_ProductId]
FOREIGN KEY ([ProductId]) REFERENCES [Operating].[Products] ([ProductId]),
CONSTRAINT [FK_Operating_PurchasesDetails_Operating_Manufacturers_ManufacturerId]
FOREIGN KEY ([ManufacturerId])
REFERENCES [Operating].[Manufacturers] ([ManufacturerId]),
CONSTRAINT [CK_Operating_PurchasesDetails_Purchase_Positive]
CHECK ([Purchase]>=(0)),
CONSTRAINT [CK_Operating_PurchasesDetails_Quantity_Positive]
CHECK ([Quantity]>(0)),
CONSTRAINT [CK_Operating_PurchasesDetails_Sale_Positive]
CHECK ([Sale]>=(0)),
CONSTRAINT [CK_Operating_PurchasesDetails_SerialNumber_Quantity]
CHECK ([Quantity]=(1) OR [Quantity]>(1)
AND [SerialNumber] like 'NS[0-1][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')
);
I get error SQL70536 when I use [SerialNumber] as a parameter.
SQL70536: The name “[SerialNumber]” is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
Note: The function is tested and is working.
Please help.
A trigger solved the problem. Thanks.
CREATE TABLE [Operating].[SalesDetails] (
[BillId] INT NOT NULL,
[SerialNumber] NVARCHAR (50) NOT NULL,
[Quantity] INT NOT NULL,
[Price] DECIMAL (19, 2) NOT NULL,
[LineTotal] AS ([Quantity] * [Price]),
[Returned] BIT DEFAULT ((0)) NOT NULL,
[Note] NVARCHAR (30) NULL,
CONSTRAINT [PK_Operating_SalesDetails_BillId_SerialNumber]
PRIMARY KEY CLUSTERED ([BillId] ASC, [SerialNumber] ASC),
CONSTRAINT [FK_Operating_SalesDetails_Operating_Sales_BillId]
FOREIGN KEY ([BillId]) REFERENCES [Operating].[Sales] ([BillId]),
CONSTRAINT [FK_Operating_SalesDetails_Operating_PurchasesDetails_SerialNumber]
FOREIGN KEY ([SerialNumber])
REFERENCES [Operating].[PurchasesDetails] ([SerialNumber]),
CONSTRAINT [CK_Operating_SalesDetails_Price_Positive] CHECK ([Price] >= (0)),
CONSTRAINT [CK_Operating_SalesDetails_Quantity_Positive] CHECK ([Quantity] > (0))
);
GO
CREATE TRIGGER [Operating].[SalePrice] ON [Operating].[SalesDetails]
INSTEAD OF INSERT AS
BEGIN
INSERT INTO [Operating].[SalesDetails]
([BillId],[SerialNumber],[Quantity],[Price],[Returned],[Note])
VALUES (
(SELECT [BillId] FROM [INSERTED]),
(SELECT [SerialNumber] FROM [INSERTED]),
(SELECT [Quantity] FROM [INSERTED]),
(SELECT [Sale] FROM [Operating].[PurchasesDetails]
WHERE [SerialNumber] = (SELECT [SerialNumber] FROM [INSERTED])),
(SELECT [Returned] FROM [INSERTED]),
(SELECT [Note] FROM [INSERTED]))
END;
Is there a shorter way to write the trigger?
I eddited the trigger as suggested:
CREATE TABLE [Operating].[SalesDetails] (
[BillId] INT NOT NULL,
[SerialNumber] NVARCHAR (50) NOT NULL,
[Quantity] INT NOT NULL,
[Price] DECIMAL (19, 2) NOT NULL,
[LineTotal] AS ([Quantity]*[Price]),
[Returned] BIT DEFAULT ((0)) NOT NULL,
[Note] NVARCHAR (30) NULL,
CONSTRAINT [PK_Operating_SalesDetails_BillId_SerialNumber]
PRIMARY KEY CLUSTERED ([BillId] ASC, [SerialNumber] ASC),
CONSTRAINT [FK_Operating_SalesDetails_Operating_Sales_BillId]
FOREIGN KEY ([BillId]) REFERENCES [Operating].[Sales] ([BillId]),
CONSTRAINT [FK_Operating_SalesDetails_Operating_PurchasesDetails_SerialNumber]
FOREIGN KEY ([SerialNumber])
REFERENCES [Operating].[PurchasesDetails] ([SerialNumber]),
CONSTRAINT [CK_Operating_SalesDetails_Price_Positive] CHECK ([Price]>=(0)),
CONSTRAINT [CK_Operating_SalesDetails_Quantity_Positive] CHECK ([Quantity]>(0))
);
GO
CREATE TRIGGER [Operating].[SalePrice] ON [Operating].[SalesDetails]
INSTEAD OF INSERT AS
BEGIN
INSERT INTO [Operating].[SalesDetails]
([BillId],[SerialNumber],[Quantity],[Price],[Returned],[Note])
SELECT I.[BillId], I.[SerialNumber], I.[Quantity],
COALESCE (I.[Price],P.[Sale]), I.[Returned], I.[Note]
FROM [inserted] AS I LEFT OUTER JOIN [Operating].[PurchasesDetails] AS P
ON I.[SerialNumber] = P.[SerialNumber]
END;
Thank you for your help.

there is already an object named '' in the database

This is my code:
CREATE TABLE supplier -- creating table supplier
(
supplierID INT NOT NULL IDENTITY,
supplierName VARCHAR(30) NOT NULL,
suppplierNo VARCHAR(10) NOT NULL,
supplierEmail VARCHAR(30) NOT NULL,
CONSTRAINT PK_supplierID PRIMARY KEY(supplierID)
)
GO
I get the the error:
Msg 2714, Level 16, State 6, Line 34
There is already an object named 'supplier' in the database.
Any help? Thanks!
Please try this code.
IF EXISTS(SELECT 1 FROM sys.tables WHERE name = 'supplier')
DROP TABLE dbo.supplier;
CREATE TABLE dbo.supplier
(
supplierID INT NOT NULL IDENTITY,
supplierName VARCHAR(30) NOT NULL,
suppplierNo VARCHAR(10) NOT NULL,
supplierEmail VARCHAR(30) NOT NULL,
CONSTRAINT PK_supplierID PRIMARY KEY(supplierID)
)
GO
You need to check if the table exists first
IF OBJECT_ID('dbo.supplier', 'U') IS NOT NULL
DROP TABLE dbo.supplier;
CREATE TABLE dbo.supplier
(
supplierID INT NOT NULL IDENTITY,
supplierName VARCHAR(30) NOT NULL,
suppplierNo VARCHAR(10) NOT NULL,
supplierEmail VARCHAR(30) NOT NULL,
CONSTRAINT PK_supplierID PRIMARY KEY(supplierID)
)
GO
If you are using 2016+ you can use
DROP TABLE IF EXISTS dbo.supplier;
CREATE TABLE dbo.supplier
(
supplierID INT NOT NULL IDENTITY,
supplierName VARCHAR(30) NOT NULL,
suppplierNo VARCHAR(10) NOT NULL,
supplierEmail VARCHAR(30) NOT NULL,
CONSTRAINT PK_supplierID PRIMARY KEY(supplierID)
)
GO

Can a value be a primary and a foreign key?

I have the following tables in my SQL Server database.
Customer is a subtype of User thus I made a reference from Customer to User.
I also want to link my customer to my reservation. I'd like to use the Foreign key in the Customer table as a PK for this relation. When I write this out in SQL Server, I get this error under "(userid)":
Invalid column 'userid'
How can I make this relation?
Create table [dbo].[User]
(
[id] int PRIMARY KEY IDENTITY (1,1) NOT NULL,
[name] varchar(50) NOT NULL,
[password] nvarchar(100) NOT NULL,
)
Create table [dbo].[Customer]
(
[userid] int FOREIGN KEY REFERENCES [dbo].[User](id) NOT NULL,
[street] varchar(40) NOT NULL,
[housenumber] varchar(10) NOT NULL,
[postalcode] varchar(10) NOT NULL,
[phonenumber] varchar(20) NOT NULL,
[email] varchar(30) NOT NULL,
)
Create table [dbo].[Reservation]
(
[id] int PRIMARY KEY IDENTITY (1,1) NOT NULL,
[datum] date NOT NULL,
[prijs] decimal NOT NULL,
[levertijd] datetime NOT NULL,
[ophaaltijd] datetime NOT NULL,
[leverAdres] varchar(60) NOT NULL,
[klantId] int FOREIGN KEY REFERENCES [dbo].[Customer](userid) NOT NULL
)
yes this is possible, try it like this
Create table [dbo].[Customer]
(
[userid] int not null,
[street] varchar(40) NOT NULL,
[housenumber] varchar(10) NOT NULL,
[postalcode] varchar(10) NOT NULL,
[phonenumber] varchar(20) NOT NULL,
[email] varchar(30) NOT NULL,
constraint PK_UserID primary key ([userid]),
constraint FK_Customer_User foreign key (userid) references [User] (id)
)
But I have to say that userid seems like an odd primary key for a table called Customer
I would so something like this :
Create table [dbo].[Customer]
(
[CustomerID] int not null identity,
[userid] int not null,
[street] varchar(40) NOT NULL,
[housenumber] varchar(10) NOT NULL,
[postalcode] varchar(10) NOT NULL,
[phonenumber] varchar(20) NOT NULL,
[email] varchar(30) NOT NULL,
constraint PK_CustomerID primary key ([CustomerID]),
constraint FK_Customer_User foreign key (userid) references [User] (id)
)
Create table [dbo].[Reservation]
(
[id] int PRIMARY KEY IDENTITY (1,1) NOT NULL,
[datum] date NOT NULL,
[prijs] decimal NOT NULL,
[levertijd] datetime NOT NULL,
[ophaaltijd] datetime NOT NULL,
[leverAdres] varchar(60) NOT NULL,
[klantId] int FOREIGN KEY REFERENCES [dbo].[Customer](customerid) NOT NULL
)

Movie Ticket System (DB)

I'm making a online movie reservation system on MVC and I am stuck at the database part on how the tables would link to each other. Does it seem alright?
ERD
CREATE TABLE [dbo].[Member]
(
[memberID] INT IDENTITY (1, 1) NOT NULL,
[memFirstName] VARCHAR (50) NULL,
[memLastName] VARCHAR (50) NULL,
[memEmailAddress] VARCHAR (50) NULL,
[memPassword] VARCHAR (15) NULL,
[memTelephone] CHAR (10) NULL,
[memAddress] VARCHAR (70) NULL,
PRIMARY KEY CLUSTERED ([memberID] ASC)
);
CREATE TABLE [dbo].[Movie]
(
[movieID] INT IDENTITY (1, 1) NOT NULL,
[movieName] VARCHAR (100) NULL,
[movieCategory] CHAR (10) NULL,
PRIMARY KEY CLUSTERED ([movieID] ASC)
);
CREATE TABLE [dbo].[Reservation]
(
[resID] INT IDENTITY (1, 1) NOT NULL,
[memberID] INT NOT NULL,
[showID] INT NOT NULL,
PRIMARY KEY CLUSTERED ([resID] ASC),
FOREIGN KEY ([memberID]) REFERENCES [dbo].[Member] ([memberID]),
FOREIGN KEY ([showID]) REFERENCES [dbo].[Show] ([showID])
);
CREATE TABLE [dbo].[Show]
(
[showID] INT IDENTITY (1, 1) NOT NULL,
[showDateTime] DATETIME NOT NULL,
[movieID] INT NULL,
CONSTRAINT [PK_Show] PRIMARY KEY CLUSTERED ([showID] ASC),
FOREIGN KEY ([showID]) REFERENCES [dbo].[Movie] ([movieID])
);