1

I wanted to know how do I check the data in the table before inserting.

For example: when I am inserting I want to check if the eventstart value is in the table with the same StartDate and same Room if so then output an error message, else insert the value.

insert into events([Text], [eventStart], [EventEnd], [Repeat], [Days], [Room], [StartDate]) 
values(Text, EventStart, EventEnd, , Days, Room, StartDate)
1
  • 1
    How about using If Exists(...) before insert ?? Commented Oct 28, 2014 at 16:53

2 Answers 2

3

I'd just use a query like this. If the count is not 0, there's at least one duplicate.

SELECT COUNT(*) 
FROM events
WHERE StartDate = @StartDate
  AND Room = @Room
  AND EventStart = @EventStart

I would have tried to put this in the context of your project (assuming you're using SqlCommand, etc), but you didn't include any of that code in your question.


If you're asking how to check for duplicates at the same time you're trying to insert records (and not immediately before, in a separate query), then I'm not sure. I wouldn't be surprised if there was a way, I just don't know it.

Sign up to request clarification or add additional context in comments.

3 Comments

Hey. Regarding "check for duplicates at the same time you're trying to insert records", I just edited my answer addressing that. Depending on how you interpret "at the same time", a UNIQUE INDEX or CONSTRAINT technically does that. It just doesn't report back in a configurable way; it just errors.
@srutzky Your answer definitely looks more efficient and, I think, more in line with what the OP wanted (at least the way I interpret his question title). If he gets it to work in his case and lets us know, I'll remove this answer.
No problem. I was just trying to let you know that there did exist a means of checking at the same time as the insert, outside of a separate operation :) .
3

Since the only relevant options here are either "row is not there" and "row is already there", there is no need for a COUNT. An IF EXISTS is more efficient as it will stop execution upon finding a row, as opposed to scaning the entire table (or index) only to find no more entries because only 1 could be there anyway.

Hence:

IF (EXISTS(
     SELECT *
     FROM   Events
     WHERE  [eventstart] = @EventStart
     AND    [StartDate] = @StartDate
     AND    [Room] = @Room
   ))
BEGIN
   RAISERROR('Row already exits!', 16, 1);
   RETURN;
END;
ELSE
BEGIN
   INSERT INTO Events
          ([Text], [eventStart], [EventEnd], [Repeat], [Days], [Room], [StartDate])
   VALUES (@Text, @EventStart, @EventEnd, @Repeat, @Days, @Room, @StartDate);
END;

The above can be done either in a stored procedure or as a parameterized query via SqlCommand in C# (or some other language).

OR

Depending on how you want to trap the condition, it is possible to handle this via a UNIQUE CONSTRAINT and then it would check upon being inserted with no need for extra code (i.e. the IF EXISTS SELECT construct). The advantages here are a) less code and b) the rule is enforced always, not just in this one instance. The disadvantages are a) the "rule" is somewhat hidden and might be forgotten until someone foolishly writes code not respecting the rule, and b) it aborts the transaction of the INSERT which I kinda try to avoid if possible. In the end, if this is a strict rule of the system, then probably best to enforce via UNIQUE CONSTRAINT, which ensures that nobody can get around the rule.

CREATE UNIQUE NONCLUSTERED INDEX [UIX_Events_fields]
   ON dbo.[Events] ([EventStart] ASC, [Room] ASC, [StartDate] ASC);

BETTER YET

Do both. The UNIQUE INDEX (not a CONSTRAINT now, and here is why) will not only enforce the rule, but it will also assist in speeding up the IF EXISTS SELECT query. This will allow you to easily manage the "error" condition and message (as opposed to trapping a SqlException and checking the ErrorCode).

1 Comment

Nice point, about EXISTS stopping as soon as a match is found. I figured there might be a way to do this in one go, just wasn't sure what that was.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.