csean
asked on
Problem creating a GetNextKey Stored Procedure
I am trying to create a GetNextKey stored procedure given
a tablename passed a parameter, but have had problems creating it.
Here is what I have so far:
-------------------------- ---------- ---------- --------
CREATE PROCEDURE GetNextKey @Tablename Varchar(10)
AS
Declare @sSQLStatement Varchar(255)
@CurKey Integer,
@NextKey Integer
select @sSQLStatement = 'select @CurKey=max(prkey) from ' +@Tablename
Exec (@sSQLStatement)
select @NextKey = @CurKey + 1
-------------------------- ---------- ---------- ------
At first I had a problem using a variable in the from
clause of an SQL statement. I got around this by building
the sql statement in a variable and executing it using
"Exec". When I did this and executed the stored proc. however, I got the following error: "Must declare variable
'@CurKey'".
I am trying to find out the following:
a) If I can use a variable in the from clause of an SQL
statement.
b) How I can assign the value to @CurKey in the SQL statement executed with "Exec".
c) How I can return @NextKey as the result of the stored
procedure.
d) If someone has created a similar procedure and can show
me ways to do it.
Thanks in advance to anyone who reads/responds to my question.
a tablename passed a parameter, but have had problems creating it.
Here is what I have so far:
--------------------------
CREATE PROCEDURE GetNextKey @Tablename Varchar(10)
AS
Declare @sSQLStatement Varchar(255)
@CurKey Integer,
@NextKey Integer
select @sSQLStatement = 'select @CurKey=max(prkey) from ' +@Tablename
Exec (@sSQLStatement)
select @NextKey = @CurKey + 1
--------------------------
At first I had a problem using a variable in the from
clause of an SQL statement. I got around this by building
the sql statement in a variable and executing it using
"Exec". When I did this and executed the stored proc. however, I got the following error: "Must declare variable
'@CurKey'".
I am trying to find out the following:
a) If I can use a variable in the from clause of an SQL
statement.
b) How I can assign the value to @CurKey in the SQL statement executed with "Exec".
c) How I can return @NextKey as the result of the stored
procedure.
d) If someone has created a similar procedure and can show
me ways to do it.
Thanks in advance to anyone who reads/responds to my question.
ASKER
Adjusted points to 200
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks Jim_SQL,
The bottom section of your response was very helpful. I never looked into temporary tables enough. That was the key to solving this problem.
Sean
The bottom section of your response was very helpful. I never looked into temporary tables enough. That was the key to solving this problem.
Sean
ASKER