简体   繁体   中英

Checking a table for an existing record before a new record is inserted

I have a details view that I am using to fill a table with values. It is now inserting values correctly but I needed to now check to see if the user is trying to enter a new record that would interfere with the previous records.

If A user enters a new event that falls on 2012-12-12 but that same user has already entered a record for 2012-12-12 then i would like an error to be thrown and the record not able to be inserted.

Just checking for a unique record of the time wont work because a different user can create an even 2012-12-12 and it will be acceptable. Only the same user cannot create the same events dates. So I know I need to check two of the fields in the table but I was unsure of how to do this checking in my code.

For example:

user 1 new event 2012-12-12 ----- ok

user 2 new event 2012-12-12 ----- ok

user 3 new event 2012-12-12 ----- ok

user 2 new event 2012-12-12 ----- should throw an error and not allow that record to be created.

user 3 new event 2012-10-12 ----- ok

EDITED

Currently I am using this to update the table:

   public void UpdateForm(Int64 requestid,
                              Decimal empid,
                              String leave,
                              DateTime startdate,
                              DateTime enddate,
                              String starttime,
                              String endtime,
                              String standby,
                              String status,
                              String rsn,
                              String remarks,
                              String approver,
                              String with,
                              String reqleave,
                              String FIRSTNAME,
                              String LASTNAME)
    {

        var CurrUser = "a03       ";

        Account.Login uusr = new Account.Login();
        CurrUser = uusr.User.Identity.Name.ToString().ToUpper();

        var sql = "update TIME.request set empid=@empid, leave=@leave, with=@with, startdate=@startdate, reqleave=@reqleave, enddate=@enddate, starttime=@starttime, endtime=@endtime, standby=@standby, status=@status, rsn=@rsn, remarks=@remarks, approver=@approver where requestid = @requestid";

        using (iDB2Connection conn = new iDB2Connection(GetConnectionString()))
        {
            conn.Open();

            using (iDB2Command cmd = new iDB2Command(sql, conn))
            {
                cmd.DeriveParameters();
                cmd.Parameters["@requestid"].Value = requestid;
                cmd.Parameters["@empid"].Value = empid;
                cmd.Parameters["@leave"].Value = leave;
                cmd.Parameters["@startdate"].Value = startdate;
                cmd.Parameters["@enddate"].Value = enddate;
                cmd.Parameters["@starttime"].Value = starttime;
                cmd.Parameters["@endtime"].Value = endtime;
                cmd.Parameters["@standby"].Value = standby;
                cmd.Parameters["@status"].Value = status;
                cmd.Parameters["@rsn"].Value = rsn;
                cmd.Parameters["@remarks"].Value = remarks;
                cmd.Parameters["@approver"].Value = approver;
                cmd.Parameters["@reqleave"].Value = reqleave;
                cmd.Parameters["@with"].Value = with;

                cmd.ExecuteNonQuery();
            }
        }
    }

create a unique Constraint on the columns

Click here for examples

ALTER TABLE <table_name>
ADD CONSTRAINT <constraint name> UNIQUE (user,date)

Edit:

as per your comment, please try this:

ALTER TABLE TIME.request
ADD CONSTRAINT uc_request UNIQUE (empid, startdate, enddate)

Create a stored procedure and have an output parameter, check if the item your inserting exists:

if exists(select 1 from table where user = @user and eventtime = @eventtime)
  begin
    set @output = 'event already exists'
  end 
else
 begin
    --Prevent DBNull output, see comments
    set @output = ''
   --Insert into table
 end

Add an output parameter to the procedure through C#

  var output = new SqlParameter() { Direction = ParameterDirection.Output, ParameterName = "@Output" };
  var cmd = new SqlCommand("procname", connection)
  cmd.Parameters.Add(output);
  //Add other params
  cmd.ExecuteNonQuery();
  if (!string.IsNullOrEmpty(output.Value))
    //Handle the error
    throw new Exception("Already exists");

A stored procedure in SQL is what you are looking for with the relevant parameters following the above, comment if there is something you don't understand.

EDIT: How to create and call a procedure

CREATE PROCEDURE [dbo].[Prefix_SomeProcName]

--Parameters you need from the front end
@User varchar(50),
@EventTime datetime,
@Output varchar(100) output

--Created by: Your name
--Created date: Todays date
--Description: To do some stuff

AS

--Do your stuff here
if exists(select 1 from table where user = @user and eventtime = @eventtime)
  begin
    set @output = 'event already exists'
  end 
else
 begin
    --Prevent DBNull output, see comments
    set @output = ''
   --Insert into table
 end

Then you need a to import System.Data.SqlClient and do the following.

using(SqlConnection con = New SqlConnection("ConnectionString")
{
   SqlCommand cmd = new SqlCommand("Prefix_SomeProcName", con);
   cmd.CommandType = CommandType.StoredProcedure;
   var output = new SqlParameter() { Direction = ParameterDirection.Output, ParameterName = "@Output" };
   //Add your other parameters
   SqlDataAdapter sda = new SqlDataAdapter(cmd);
   DatatTable dt = New DataTable();
   sda.Fill(dt);
}

The DataTable will now have the contents of the procedure if there is a select statement in it. Also, after the Fill() command you can access output.Value as mentioned in the above code.

If this behaviour is epxected and you don't want the overhead of trapping the exception, you can check for existence in the same action as the isnert:

insert into myTable(...)

select ...
where not exists (select 1 from myTable where....)

This will work in Sql Server, but not with MySql.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM