Discussion Locked

Dup Key with SQL Server getdate()

0 helpful
9 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I am using Visual Basic 6.0 and SQL Server 7.0, both with the latest service packs. The user types in a number and presses enter.
Using ADO, I then perform an insert into a table that has the number entered by the user and a datetime field as the key. Inserted is the number and getdate(). How is it possible that I am getting duplication keys??? This exact application worked in SQL 6.5!!! I know I have a fast computer, but hand keying the number pressing enter, and two separate calls to the database that both return the exact same millisecond is not feasible. Is there some new sort of buffering is SQL Server 7.0? Any ideas???

9 replies

by mtnsqs

I don;t have SQL server 7 here at the moment to check, but I thought that under SQL 7 Getdate returns a date with hours and minutes ONLY - I think there might be a flag to get it to be more accurate but I am not sure - don't have the refernces with me

by chrandrob

In SQL 7.0, getdate() only displays the DateTime value down to the minute, but it still stores it to the millisecond.

The odds are astronomical that it would be able to do the function twice within a millisecond. However, if you are actually entering a value by using the getdate() function, the value being entered is not down to the millisecond.

What you need to do is give the field a default value of getdate() and do not insert a value into it. This will allow the server to enter the date via the system and not programmatically.

I would, however, appeal to you to change your primary key. You can add an integer field to the table and make it an identity field and use it as the primary key. Since it would be a new column and an identity field, you probably would not need to change any of your existing code to allow for this.

If you programmatically set up a loop to insert values into the table and cause the system to insert the default value of getdate(), it will be able todo two inserts within a millisecond and it will fail.

Whenever possible and feasible, I always use an integer identity field for my primary key.

by bowjangles

SQL Server 7.0 getdate() function returns a date but not down to the millisecond, only down to the minute. The odds of creating a duplicate key are still slim but have obviously happened. I would actually recommend you change your primary key to maybe an auto counter or something to ensure you will not have duplication. If you were to use an out counter it wouldnt be bad because the samller the number in the key the earlier the date. Let me know if this was useful info. Thanks

Justin

by ambily

I suggest you try the insert the number only after altering the table and using the current_timestamp as the default constraint for your date time col.

Hope that helps

This discussion is closed to new replies.