如何为唯一列编写存储过程 [英] how to write stored procedure for unique column

查看:93
本文介绍了如何为唯一列编写存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请有人告诉我如何在存储过程中插入唯一列,
就像我想通过存储过程将作为主键,名称,地址和电子邮件ID的ID插入表一样,
但要求是这样,重复的emailid不能通过存储的过程插入.

我该怎么做,我能够插入所有数据,但如何使emailid(允许重复的emailid)
请有人告诉.......

Pls some one tell that how to insert unique column in stored procedure,
Like i want to insert id which is primary key, name, address and emailid by the stored procedure into table,
but requirement is this, that duplicate emailid can not be inserted by stored procedue.

how can i do this, i am able to insert all data but how can i make emailid(dosent allow duplicate emailid)
pls some one tell this.......

推荐答案

首先检查该值,然后插入或不插入记录

Check for the value first then either insert the record or not

IF NOT EXISTS(SELECT emailId FROM table where emailId = @emailId)
  INSERT ...


而不是在存储过程中执行此操作,为什么不只在表定义中将emailid字段设置为唯一?
如果这是一个特定的分配,并且必须在过程中完成,那么您将需要首先运行select语句以确保emailid不存在,然后在搜索未返回任何结果的情况下插入新记录.在这种情况下,您可能还希望该过程向调用方抛出一个描述性错误,表明电子邮件ID不是唯一的.
Rather than do this in the stored procedure, why would you not just set the emailid field as unique in the table definition?
If this is a specific assignment and it must be done in the procedure then you would need to run a select statement first to ensure that the emailid does not exist and then insert the new record if the search returns no results. In this situation, you may also wish to have the procedure throw a descriptive error to the caller indicating that the email id is not unique.


这篇关于如何为唯一列编写存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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