【问题标题】:How do I insert Windows form data in 2 different tables?如何在 2 个不同的表中插入 Windows 表单数据?
【发布时间】:2015-08-10 14:02:03
【问题描述】:

我创建了 2 个表 student and course

中的字段

学生表是(student_id, student_name,.....).中的字段

课程表是(course_id, student_id,......)。填写student and course 表的Windows 表单是一样的。
我能够在学生表中插入学生数据。

现在,我的问题是如何在课程表中填写 student_id,因为我不知道 student_id)?
到目前为止,我可以分别插入学生和课程数据,而课程表中的 student_id 为空。

Dim query As String = "INSERT INTO tbl_student (student_name, student_address, student_gender,student_dob,student_phone)" & _
                "VALUES (" & _
                "'" & name & "'," & _
                "'" & address & "'," & _
                "'" & gender & "'," & _
                "'" & dob & "'," & _
                "'" & phone & "'," & _
                "'" & phone & "' )"
Dim query1 As String = "INSERT INTO tbl_course (student_id, course_name)" & _
                "VALUES (" & _
                "'" & student_id & "'," & _
                "'" & cname & "' )"


我不确定要填写第二个查询的 student_id 什么。第一个表中的 student_id 是一个自增字段。

【问题讨论】:

  • 我已经编辑了上面的问题,将我的代码放入...
  • 在第一次插入后选择 SCOPE_IDENTITY()。请!在语句中使用参数

标签: sql-server vb.net winforms windows-forms-designer


【解决方案1】:

在第一个 INSERT 中,您可以添加 OUTPUT 子句以获取当前 INSERT 的 Student_id,而无需额外请求。你只需要处理输出。

INSERT INTO ....
OUTPUT inserted.student_id
VALUES (...);

如果 INSERT 由于键冲突而失败,SQL-Server 会返回一个空的结果集。

如果您使用 SCOPE_IDENTITY(),如果插入失败,您可能会从较早插入的学生那里获取 ID。所以我建议使用 OUTPUT

【讨论】:

  • 我使用了你说的上面的代码......但是现在我如何让student_id使用消息框显示或使用student_id?
  • 您是否从 SQL-Server 检索了 student_id 的值?此值必须是您的第二个查询的输入。我不是 VB.NET 的人,所以不能说如何编写消息框左右的代码。在 VBA 中,我会打开一个 Recordset 以从 SQL-Server 获取结果集并处理第一行
猜你喜欢
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 2017-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-14
  • 2013-10-29
相关资源
最近更新 更多