简体   繁体   English

插入带有两个相关表的SQL命令

[英]Insert Into SQL command with two related tables

i have 3 tables in my site. 我的网站上有3张桌子。

  1. Users 用户数
  2. Threads 线程数
  3. Comments 评论

I connected the comments primary key to Threads comments field. 我将注释主键连接到“线程注释”字段。 I want to use insert into command while feeding comments to specific threads. 我想在向特定线程提供注释时使用插入命令。

How do i write the command?!? 我该如何编写命令?!

is it like this: 像这样吗?

 string myCommand="INSERT INTO [Threads].[Comments] VALUES(....";

Will the messages be inserted into a specific thread? 消息会插入到特定线程中吗? What if i want to insert data to both simultaneously.. eg a headline to a thread and a date to the comment...can i combine two commands into one? 如果我想同时向两者插入数据怎么办..例如,线程的标题和注释的日期...我可以将两个命令合并为一个吗?

You have to create two separate INSERT statements. 您必须创建两个单独的INSERT语句。 You can wrap them in a transaction to ensure that neither are committed unless they are both successful. 您可以将它们包装在事务中,以确保除非它们都成功,否则都不要提交。

您已经将外键设置为从前到后,如果线程表中有一个外键链接到注释表的主键,那么一个注释可以与许多线程相关,但是一个线程只能有一个注释。

You still need two INSERT statements, but it sounds like you want to get the IDENTITY from the first insert and use it in the second, in which case, you might want to look into OUTPUT or OUTPUT INTO: http://msdn.microsoft.com/en-us/library/ms177564.aspx 您仍然需要两个INSERT语句,但这听起来像您想从第一个插入中获取IDENTITY并在第二个插入中使用它,在这种情况下,您可能希望研究OUTPUT或OUTPUT INTO: http : //msdn.microsoft .com / zh-CN / library / ms177564.aspx

(my answer to the same question previously asked: SQL Server: Is it possible to insert into two tables at the same time? ) (我对先前询问的同一问题的回答: SQL Server:是否可以同时插入两个表中?

Use two commands to insert into Threads and Comments. 使用两个命令插入“线程”和“注释”。 First insert into Threads and grab the id: 首先插入线程并获取ID:

string myCommand = "INSERT INTO [Threads] (...";
// execute
string myCommand = "SELECT SCOPE_IDENTITY()";
// execute - put in thread ID

Then insert into comments using the thread ID 然后使用线程ID插入注释中

string myCommand = "INSERT INTO [Comments] (" + ThreadID + "...";

There is no real value or point in somehow accomplishing this in a single INSERT Command. 以某种方式在单个INSERT命令中完成此操作没有任何实际价值或意义。

Edit Changed @@IDENTITY to SCOPE_IDENTITY() per comment suggestions. 编辑更改@@ IDENTITY每评论建议SCOPE_IDENTITY()。 Thanks! 谢谢!

I'd create a stored procedure and put both insert's into one transaction within the SP. 我将创建一个存储过程,并将两个插入项都放入SP中的一个事务中。 You can use @@SCOPE_IDENTITY to get the ID from the insert into threads and use that in your insert into the comments table: 您可以使用@@ SCOPE_IDENTITY从插入线程中获取ID,并在插入注释表中使用该ID:

INSERT INTO [Threads] (...

INSERT INTO [Comments]
SELECT 
     @@SCOPE_IDENTITY,
     OtherValues ...

You could use a transaction as previously stated to make it more robust. 您可以使用前面所述的事务来使其更加健壮。 Call your SP from your C# code using a SQL command. 使用SQL命令从C#代码调用SP。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM