-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmany.sql
90 lines (74 loc) · 2.2 KB
/
many.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
CREATE DATABASE YOUTUBE
GO
USE YOUTUBE
Create table Students
(
Id int primary key identity,
StudentName nvarchar(50)
)
Go
Create table Courses
(
Id int primary key identity,
CourseName nvarchar(50)
)
Go
Create table StudentCourses
(
StudentId int not null foreign key references Students(Id),
CourseId int not null foreign key references Courses(Id)
)
Go
---------------------------------
Declare @StudentName nvarchar(50) = 'Sam'
Declare @CourseName nvarchar(50) = 'SQL Server'
Declare @StudentId int
Declare @CourseId int
-- If the student already exists, use the existing student ID
Select @StudentId = Id from Students where StudentName = @StudentName
-- If the course already exists, use the existing course ID
Select @CourseId = Id from Courses where CourseName = @CourseName
-- If the student does not exist in the Students table
If (@StudentId is null)
Begin
-- Insert the student
Insert into Students values(@StudentName)
-- Get the Id of the student
Select @StudentId = SCOPE_IDENTITY()
End
-- If the course does not exist in the Courses table
If (@CourseId is null)
Begin
-- Insert the course
Insert into Courses values(@CourseName)
-- Get the Id of the course
Select @CourseId = SCOPE_IDENTITY()
End
-- Insert StudentId & CourseId in StudentCourses table
Insert into StudentCourses values(@StudentId, @CourseId)-
-----------------------------------------------------------------
Create procedure spInsertIntoStudentCourses
@StudentName nvarchar(50),
@CourseName nvarchar(50)
as
Begin
Declare @StudentId int
Declare @CourseId int
Select @StudentId = Id from Students where StudentName = @StudentName
Select @CourseId = Id from Courses where CourseName = @CourseName
If (@StudentId is null)
Begin
Insert into Students values(@StudentName)
Select @StudentId = SCOPE_IDENTITY()
End
ELSE
PRInt 'Student already there'
If (@CourseId is null)
Begin
Insert into Courses values(@CourseName)
Select @CourseId = SCOPE_IDENTITY() --the id that just inserted
End
else
print 'Student select this course'
Insert into StudentCourses values(@StudentId, @CourseId)
End