[英]Create a table in SQL Server where the name is a variable in C#?
Using Visual Studio and SSMS. 使用Visual Studio和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? 从那里,我可以创建一个名为
CreateUserCourses
的存储过程,在其中创建一个新表,用户在其中输入(他们的用户名)是新表的名称吗?
Sure you can, but why? 当然可以,但是为什么呢?
Supposing you have a User
table and a Course
table. 假设您有一个
User
表和一个Course
表。 Then just make a 3rd table which maps those tables together Called UserCourses
. 然后只需制作第三个表即可将这些表映射在一起,称为
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 . 这称为“多对多”(映射表),它将包含
User
和Course
的ID以及其他任何相关信息。
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 entities 1 A and B in which A may contain a parent instance for which there are many children in B and vice versa.
多对多关系是一种基数,是指两个实体1 A和B之间的关系,其中A可能包含一个父实例,而B中有许多子对象,反之亦然。
For example, think of A as Authors, and B as Books.
例如,将A视为作者,将B视为书籍。 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 SQL查询可能看起来像这样
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.