如果复合主键存在,如何在sqlserver表中插入 [英] how to insert in sqlserver table if composite primary key present

查看:181
本文介绍了如果复合主键存在,如何在sqlserver表中插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先生

i希望通过storeprocedure插入到表中,如果复合主键存在3个属性,如果我在表中插入3个相同的int类型否则会引发错误,如何处理错误请帮助我

sir
i want to insert into a table through storeprocedure if a composite primary key is present having 3 attribute,if i have insert 3 same int type no into table it is raising a error,how to handle the error pls help me

推荐答案

主键必须始终是唯一的。对于复合主键也是如此。

当你的主键由三个int a,b,c组成时,你不能插入两行具有相同的a,b,c值。

现在检查你的要求:当这种组合再次出现时会发生什么?一个错误?然后只需将消息更改为用户更易于理解。更新?然后检查是否存在组合,如果它已经存在,则执行更新查询而不是插入查询。
A primary key must always be unique. That holds also true for composite primary keys.
When your primary key consists of three int a,b,c then you must not insert two rows with the same values of a,b,c.
Now check your requirements: what is expected to happen when such a combination recurs? An error? Then just change the mesage to become more intellegible to the user. An update? Then check for the presence of the combination, and if it is already present, do an update query instead of an insert query.


如果您有复合键并且想要在其中插入值。

然后尝试以下代码



将忽略插入HotelBooking(RoomID,RegisterDate,CustomerName,Gender,Address,BillAmount)值('R1002' ,'12 / 12/2018','Adam Ponting','男','悉尼澳大利亚','1132.11')

ON DUPLICATE KEY UPDATE RoomID = values(RoomID),RegisterDate = values( RegisterDate);
If you have composite key and want to insert values into it.
Then try below code

insert ignore into HotelBooking(RoomID, RegisterDate , CustomerName , Gender , Address , BillAmount ) values ('R1002', '12/12/2018','Adam Ponting','Male', 'Sydney Australia' , '1132.11')
ON DUPLICATE KEY UPDATE RoomID =values(RoomID), RegisterDate =values(RegisterDate );


这篇关于如果复合主键存在,如何在sqlserver表中插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆