I have a main table that stores the names of all the tables in that database & the next pkey that the record in the respective table should have when a new record is inserted in it(This is the requirement). I am writing a function which returns the primary key of the tablename entered.
The function that i have written is as follows:
CREATE Function next_pkey(@in_tablename varchar(250),@in_increment int)
DECLARE @nextid int
DECLARE @out_nextid int
SET @out_nextid = -1
UPDATE main_ids SET nextid = nextid + @in_increment WHERE tablename = @in_tablename
IF (@@ROWCOUNT = 0)
INSERT INTO main_ids (tablename, nextid) VALUES (@in_tablename, 1 + @in_increment)
SET @nextid = 1
SELECT @nextid = nextid - @in_increment FROM main_ids WHERE tablename = @in_tablename
IF (@@ERROR = 0)
SET @out_nextid = @nextid
This function gives 2 erros as mentioned below:
Invalid use of 'UPDATE' within a function.
Invalid use of 'INSERT' within a function.
I have the following query:
Is an update statement allowed in a function?
Can you tell me what should i do so that this function executes properly???
The types of statements that are valid in a function include:
DECLARE statements can be used to define data variables and cursors that are local to the function.
Assignments of values to objects local to the function, such as using SET to assign values to scalar and table local variables.
Cursor operations that reference local cursors that are declared, opened, closed, and deallocated in the function. FETCH statements that return data to the client are not allowed. Only FETCH statements that assign values to local variables using the INTO clause are allowed.
SELECT statements containing select lists with expressions that assign values to variables that are local to the function.
UPDATE, INSERT, and DELETE statements modifying table variables that are local to the function.
EXECUTE statements calling an extended stored procedure.