我想插入数据库新客户。 要做到这一点,我必须放入表CLIENT FirstName,LastName,Postcode。对于第二个表CLIENTGROUP,我必须放置客户组,如访客或VIP。第一个表ID是第二个外键。
当我在CLIENT中添加新客户时,ID会自动增加。如何在CLIENTGROUP中进行更新id的查询? 我将不得不加入两个查询
var connection = OpenConnection();
var command = connection.CreateCommand();
command.CommandText = "insert into Klient(FirstName,LastName,Postcode) values (@FirstName, @LastName, @Postcode)";
AddParameterString(command, "@FirstName", model.FirstName);
AddParameterString(command, "@LastName", model.LastName);
AddParameterDecimal(command, "@Turnover", model.Postcode);
command.ExecuteNonQuery();
command.CommandText = "insert into ClientGroup (ClientGroup) values (@ClientGroup)";
AddParameterString(command, "@ClientGroup", model.ClienGroup);"
command.ExecuteNonQuery();
但我根本不知道如何。
答案 0 :(得分:1)
将SELECT SCOPE_IDENTITY()
添加到第一个插入查询中,这将为您提供插入客户的ID。在c#端使用ExecuteScalar
方法(如果使用ADO.NET)。查询:
INSERT INTO Customer (/*...*/) VALUES (/*...*/)
SELECT SCOPE_IDENTITY()
C#:
var connection = OpenConnection();
var command = connection.CreateCommand();
command.CommandText = @"
insert into Klient(FirstName,LastName,Postcode) values (@FirstName, @LastName, @Postcode)
SELECT SCOPE_IDENTITY()";
AddParameterString(command, "@FirstName", model.FirstName);
AddParameterString(command, "@LastName", model.LastName);
AddParameterDecimal(command, "@Turnover", model.Postcode);
int customerId = (int) command.ExecuteNonQuery();
// ...use customerId in the second insert
您也可以考虑使用事务包装这两个插入查询。
答案 1 :(得分:0)
您的代码将如下所示。假设ClientId
是主键列的名称。同时为外键设置自动增量(在ClientGroup
表中)。
var connection = OpenConnection();
var command = connection.CreateCommand();
command.CommandText = "insert into Klient(FirstName,LastName,Postcode) values (@FirstName, @LastName, @Postcode) Select Ident_Current('Klient')";
AddParameterString(command, "@FirstName", model.FirstName);
AddParameterString(command, "@LastName", model.LastName);
AddParameterDecimal(command, "@Turnover", model.Postcode);
int foreignKey = command.ExecuteScaler();
command.CommandText = "insert into ClientGroup (ClientId,ClientGroup) values (@ClientId, @ClientGroup)";
AddParameterString(command, "@ClientId", foreignKey);
AddParameterString(command, "@ClientGroup", model.ClienGroup);
command.ExecuteNonQuery();