c# - how can i update SQL table logic -
i have table structured as,
table 3 fruit id - foreign key (primary key of table 1) crate id - foreign key (primary key of table 2)
now need execute query will,
update crate id
of fruit id
if fruit id
is in table, , if not insert record in table 3 new record.
this got in code right now,
private void relatefuirtwithcrates(list<string> selectedfruitids, int selectedcrateid) { string insertstatement = "insert fruit_crate(fruitid, crateid) values " + "(@fruitid, @crateid);"; ?? don't think if it's right query using (sqlconnection connection = new sqlconnection(connectionstring())) using (sqlcommand cmd = new sqlcommand(insertstatement, connection)) { connection.open(); cmd.parameters.add(new sqlparameter("@fruitid", ????? not sure goes in here)); cmd.parameters.add(new sqlparameter("@crateid",selectedcrateid)); }
you can "upsert" merge
syntax in sql server:
merge [sometable] target using (select @fruitid, @crateid) source (fruitid, crateid) on (target.fruitid = source.fruitid) when matched update set crateid = source.crateid when not matched insert (fruitid, crateid) values (source.fruitid, source.crateid);
otherwise, can use like:
update [sometable] set crateid = @crateid fruitid = @fruitid if @@rowcount = 0 insert [sometable] (fruitid, crateid) values (@fruitid, @crateid)
Comments
Post a Comment