Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从代码中将主键作为参数插入SQL数据库表中?_C#_Sql_Sql Server_Database - Fatal编程技术网

C# 如何从代码中将主键作为参数插入SQL数据库表中?

C# 如何从代码中将主键作为参数插入SQL数据库表中?,c#,sql,sql-server,database,C#,Sql,Sql Server,Database,我有两个表(主表和次表)。主表包含主键,主键是辅助表的外键。每当我在主表中插入新行时,我都需要获取它的主键并将其插入到次表中。我在将主键作为参数时遇到困难。我需要帮助 string connString=“数据库=MyServerDB;服务器=ATLW732FV000169\SQLEXPRESS;集成安全性=True;连接超时=30”; SqlConnection myConnection=新的SqlConnection(connString); 尝试 { myConnection.Open(

我有两个表(主表和次表)。主表包含主键,主键是辅助表的外键。每当我在主表中插入新行时,我都需要获取它的主键并将其插入到次表中。我在将主键作为参数时遇到困难。我需要帮助

string connString=“数据库=MyServerDB;服务器=ATLW732FV000169\SQLEXPRESS;集成安全性=True;连接超时=30”; SqlConnection myConnection=新的SqlConnection(connString); 尝试 { myConnection.Open(); }
捕获(例外e) { Console.WriteLine(如ToString()); }

使用(SqlCommand命令=新的SqlCommand(“插入到主表(TransactionType,Country)”值(@TransactionType,@Country);”+ “插入辅助_表(BookingID,TripID)值(@BookingID,@TripID);”,myConnection)) { //声明主表参数 command.Parameters.AddWithValue(“@transactionType”,“S”); command.Parameters.AddWithValue(“@country”、“US”); //声明辅助表参数 command.Parameters.Add(“@bookingID”,****);//不确定如何将bookingID(priamry键)插入辅助表 command.Parameters.AddWithValue(“@tripID”,“tr”); 尝试 { Int32 lines=command.ExecuteOnQuery(); 控制台写入线(“受影响的行”+行); } catch(SqlException-ex) { 控制台写入线(例如消息); } }
在主表上定义一个触发器,该触发器将获取插入数据的主键并将其插入到辅助表中。

执行以下操作:

在首次插入后-

DECLARE @var int

@var = select top 1 [pk] from table1 order by pk desc
这将获得表1中@var为主键的最新记录,然后简单地

insert into table2 ([fk]) values (@var)

这是在存储过程中最容易做到的,这被认为是最佳实践(永远不要在.NET代码中使用内联SQL)。

您可以通过SQL中的一个StoredProcess插入到主表和辅助表中:

声明@Primary_Id int

将值(@TransactionType,@Country)插入主表(TransactionType,Country) 设置@Primary\u Id=@@identity

将值(@BookingID,@Primary_Id)插入辅助_表(BookingID,TripID)

然后在代码中:
command.CommandType=CommandType.StoredProcedure;

到目前为止,您的代码是什么样子的?事实上,我们无法给出答案,因为我们无法确定您的文本与实际代码之间的关系。您能提供一些代码吗?添加了我的代码。谢谢我将创建存储过程并使用scope\u Identity()收集并返回,而不是内联sql。
insert into table2 ([fk]) values (@var)