The actual method that IDENT_CURRENT()
uses to retrieve the current identity value is not documented as far as I'm aware. It's possible it retrieves this directly from memory using internal functions you aren't allowed to run. You can imagine what it probably does and simulate that to some degree, e.g.
SELECT COALESCE(last_value, seed_value)
FROM sys.identity_columns
WHERE [object_id] = OBJECT_ID('dbo.tablename'));
You can compare the performance yourself, on your system, with code like this:
SELECT SYSDATETIME();
GO
DECLARE @i INT = IDENT_CURRENT('dbo.tablename');
GO 10000
SELECT SYSDATETIME();
GO
DECLARE @i INT = (SELECT MAX(column) FROM dbo.tablename);
GO 10000
SELECT SYSDATETIME();
GO
DECLARE @i SQL_VARIANT = (SELECT COALESCE(last_value,seed_value)
FROM sys.identity_columns
WHERE [object_id] = OBJECT_ID('dbo.tablename'));
GO 10000
SELECT SYSDATETIME();
(Note that seed_value
and last_value
are of type SQL_VARIANT
, since IDENTITY
columns can be implemented using a number of numeric types, so that is why @i
is not an INT
in that case.)
My guess is you aren't going to see any negligible differences there, except that the MAX
approach should take longer as the table gets bigger (which is why I'm not going to bother posting my results from this test - I have no idea how many rows are in your table, how wide is the index that will be used for the MAX
, etc). You're going to have to determine on your own which of these approaches is faster in your scenario, using your hardware and your data, or whether it really isn't going to matter.
HOWEVER...
...as I've stated in the comments, which of these is faster is irrelevant, because the logic you're using in the first place to decide between any of them is flawed. Insert the row, grab the value using SCOPE_IDENTITY()
or the OUTPUT
clause, and then move on. Don't try to game the system and predict what IDENTITY
value will eventually be inserted, because I guarantee you this will fail. This is not an assumption - it has been proven over, and over, and over, and over...
For example:
- For the last time, NO, you can't trust IDENT_CURRENT().