Click here to Skip to main content
15,896,726 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
if a student enters his name in one textbox and selects many subjects he has from listbox and submits ,
what will be the design of table to insert student name and selected subjects, subjects vary according to student choice, and what will be the query for this ?
Posted

Well, this is not the kind of question we like here. You have to use what you have learned, or learn what you have to.
What you described here needs at least tree tables, thus can not be performed in one insert statement (not query!), but you can combine them. The minimalist design could be this one:
Students table:
SQL
CREATE TABLE [dbo].[students](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[name] [varchar](50) NOT NULL,
 CONSTRAINT [PK_students] PRIMARY KEY ([id] ASC)
)

Subjects table:
SQL
CREATE TABLE [dbo].[subjects](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[title] [varchar](50) NOT NULL,
 CONSTRAINT [PK_subjects] PRIMARY KEY (	[id] ASC )
)

Application table:
SQL
CREATE TABLE [dbo].[application](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[student_id] [int] NOT NULL,
	[subject_id] [int] NOT NULL,
 CONSTRAINT [PK_application] PRIMARY KEY ( [id] ASC ),
 CONSTRAINT [FK_application_students] FOREIGN KEY([student_id]) REFERENCES [dbo].[students] ([id]),
 CONSTRAINT [FK_application_subjects] FOREIGN KEY([subject_id]) REFERENCES [dbo].[subjects] ([id])
)

And now, let's add some subjects first:
SQL
insert into subjects(title) values('Math');
insert into subjects(title) values('Chimie');
insert into subjects(title) values('English');


And finally, let's add a student with it's applications in a single query:
SQL
insert into students(name) values('John');
DECLARE @newid int;
SET @newid = (SELECT IDENT_CURRENT('students'));
insert into application(student_id,subject_id) values(@newid, 1);//Math
insert into application(student_id,subject_id) values(@newid, 3);//English
 
Share this answer
 
You need following tables;
Student - StudentId, Name - Master table for students
Subject - SubjectId, Name - Master table for subjects
StudentSubjects - Id, StudentId, SubjectId - Mapping table to know subjects mapped to a student

For retrieving all the subject information related to a student you have to join all the above 3 tables as below;

SQL
SELECT SB.STUDENTID,S.NAME AS STUDENTNAME,SJ.NAME AS SUBJECTNAME FROM STUDENTSUBJECTS SB INNER JOIN STUDENT S ON SB.STUDENTID=S.STUDENTID
INNER JOIN SUBJECT SJ ON SB.SUBJECTID=SJ.SUBJECTID WHERE SB.STUDENTID=1
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900