tryingtotryhard
tryingtotryhard

Reputation: 134

Create a table in SQL Server where the name is a variable in C#?

Using Visual Studio and SSMS.

I have a form where a user registers a username and it's stored like this:

List<SqlParameter> sqlNewTable = new List<SqlParameter>();
sqlNewTable.Add(new SqlParameter("Username", txtUser.Text));
DAL.ExecSP("CreateUserCourses", sqlNewTable);

From there, can I create a stored procedure called CreateUserCourses in which it creates a new table where the users input (their username) is the name of a new table?

Upvotes: 0

Views: 73

Answers (1)

TheGeneral
TheGeneral

Reputation: 81583

Sure you can, but why?

Supposing you have a User table and a Course table. Then just make a 3rd table which maps those tables together Called UserCourses. This is called a Many-to-Many (mapping table) and it will containing an ID of both the User, and Course and any other relevant information .

This will make your life a lot easier going forward

Many-to-many (data model)

A many-to-many relationship is a type of cardinality that refers to the relationship between two entities1 A and B in which A may contain a parent instance for which there are many children in B and vice versa.

For example, think of A as Authors, and B as Books. An Author can write several Books, and a Book can be written by several Authors

Example

student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id     // mapping table

SQL queries could look like this

Getting all students for a class

SELECT s.student_id, last_name
FROM student_classes sc 
INNER JOIN students s ON s.student_id = sc.student_id
WHERE sc.class_id = X

Getting all classes for a student

SELECT c.class_id, name
FROM student_classes sc 
INNER JOIN classes c ON c.class_id = sc.class_id
WHERE sc.student_id = Y

Entity framework queries could look like this

Getting all students for a class

var students = db.Students.Where(x => x.StudentClasses
                                       .Any(y => y.ClassId == 1);

Getting all classes for a student

var classes = db.classes.Where(x => x.StudentClasses
                                     .Any(y => y.StudentId == 1);

Upvotes: 1

Related Questions