create procedure USP_Insert_Update_emp(@IntId int ,@chvmobile (20),@Chvename varchar(20),@intOutparameter int)
as
begin
if (@IntId = 0) --Means user want to insert. /*
/* Then I check here that, if mobile already
exists then (In table id is auto generated) and
for inserting user will enter @IntId as 0 that
means he/she want to insert and now In table id is
autogenerated and name and mobile is inserted */
set @intOutparameter = -1 */
else /*If user enter @IntId as nonzero i.e. id which he/she want update.*/
update tblemp set name =@Chvename,
mobile = @chvmobile
where id = @IntId
end
现在:
1
。如果用户插入例如“9975072314”,则在数据库中插入“rishi”值。哪个是接受的。
2
。如果用户输入具有相同手机号码的值,则会将@intoutput参数设为-1,这是可以接受的。
3
。现在在数据库tablemps中是:
id name mobileNo
1 nn 123
2 cvb 1234
.
.
**.
10 Rishi 9975072314**
4
。现在用户更新Id = 2,它使表中的值为:
id name mobileNo
1 nn 123
2 cvb 9975072314 /* Updatable values which I don't want. */
.
.
**.
10 Rishi 9975072314**
现在如何避免表中的重复更新?
答案 0 :(得分:2)
所以你不想在mobileNo列中重复一次?
如果mobile no不是可选字段,则可以在列上定义UNIQUE约束:
e.g。
ALTER TABLE tblemp
ADD CONSTRAINT uqtblempMobileNo UNIQUE(mobileNo)
如果您尝试在表格中添加重复的手机号码,则会出现错误。但这意味着,你不能拥有多个带有空白/空移动号码的记录 - 我可以看到你很可能没有为所有人提供移动号码。
看起来您在INSERT代码路径中进行了检查,以确保手机号码尚不存在。您还可以在更新之前检查UPDATE路径吗?
IF (ISNULL(@mobileno, '') <> ''
AND EXISTS (SELECT * FROM tblemp WHERE mobileno = @mobileno AND id <> @Id))
BEGIN
-- A record already exists with this (non-blank) mobile number, and it's NOT the record we're updating. So prevent the UPDATE...
END