[英]How to increment in id in foreign key in SQL Server
我有两个数据库表dtadd
其中列address
, city
和id
是外键,另一个表是dtperson
,其列name
, age
和id
是主键。 我只想知道如何在外键中增加id。
这是我的代码:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=.;database = mydata2;integrated security = true";
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count-1 ; i++)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into dtperson1 (name,age)values('" + dataGridView1.Rows[i].Cells[0].Value + "','" + dataGridView1.Rows[i].Cells[1].Value + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into dtadd (address,city)values('" + dataGridView1.Rows[i].Cells[2].Value + "','" + dataGridView1.Rows[i].Cells[3].Value + "')";
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
MessageBox.Show("datainserted");
}
首先,您需要在要获取最近添加的行的值的数据库中将主键设置为自动增量, 在这里
是您要寻找的问题。 但是在您的情况下,如果您想在添加行之后获得人的价值,则可以使用
using (var con = new SqlConnection(ConnectionString)) {
int newID;
var cmd = "insert into dtperson1 (name,age)values(@val1,@val2);SELECT CAST(scope_identity() AS int)";
using (var insertCommand = new SqlCommand(cmd, con)) {
insertCommand.Parameters.AddWithValue("@val1", dataGridView1.Rows[i].Cells[0].Value);
insertCommand.Parameters.AddWithValue("@val2", dataGridView1.Rows[i].Cells[1].Value);
con.Open();
newID = (int)insertCommand.ExecuteScalar();
}
}
您需要使用dtperson
表中的autoincrement设置主键列。
将行插入dtperson
,您需要获取最后插入的记录id
select @id = Scope_Identity()
使用此id
作为dtadd
表的外键ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.