June 9, 2010 at 11:14 pm
The following code:
create FUNCTION [dbo].[ufn_GenPK]
( @table varchar(100))
RETURNS int
BEGIN
DECLARE @ReturnValueint = -1
DECLARE @junkchar(128)
SELECT @junk= gpk_pk from generatepk WHERE gpk_pk = @table
IF @@ROWCOUNT = 1
begin
update generatepk set gpk_currentnumber = gpk_currentnumber + 1 where gpk_pk = @table
select @returnvalue = generatepk where gpk_pk = @table
end
RETURN @ReturnValue
END
GO
Gets the following error:
Msg 443, Level 16, State 15, Procedure ufn_GenPK, Line 13
Invalid use of a side-effecting operator 'UPDATE' within a function.
How can I do this? I am trying to get the next pk value for a table from the correct record?
Thanks,
Mike
June 9, 2010 at 11:17 pm
It's not going to happen using a function because a function isn't allowed to update or insert into "real" tables... period.
--Jeff Moden
Change is inevitable... Change for the better is not.
June 9, 2010 at 11:22 pm
Jeff,
What would you recommend to make sure I don't get duplicate primary keys? Should I do it as a standard proc?
Mike
June 9, 2010 at 11:33 pm
What's wrong with an identity column?
It'll save you a lot of grief in the long run. The manually updated key in a sequence table can be done, but there are far more ways to do it wrong (causing occasional duplicate values and/or major performance problems) than there are ways to do it right.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
June 9, 2010 at 11:57 pm
legacy code issues. Need the primary key for child record(s).
June 10, 2010 at 1:21 am
Identity column with either scope_identity or the output clause?
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
June 10, 2010 at 7:18 am
mike 57299 (6/9/2010)
Jeff,What would you recommend to make sure I don't get duplicate primary keys? Should I do it as a standard proc?
Mike
I agree with Gail. Even though it's legacy code, if it can withstand the making of a function, it can also withstand the changes she suggested and it can be done in such a fashion as to preserve what's already in the column. It's also the best solution because you'll never get a deadlock from the incrementing of the ID. You might get deadlocks from any other method if a multi-table transaction is ever involved (been there and done that).
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply