I'm working on a procedure that will take the min and max values from an identity column, and return a cursor with all the values that are missing between the min and the max. Here is what I have so far:
CREATE PROCEDURE dbo.nonsequential
@table1 varchar(25),
@idfield as varchar(25)
as
DECLARE @min int
DECLARE @max int
DECLARE @Records Cursor
DECLARE @s varchar(255)
set @s='create procedure #temp_a as declare @r int select @r=min('+@idfield+') from '+@table1+' return@r'
EXEC (@s)
EXEC @min=exec(#temp_a)
set @s='create procedure #temp_b as declare @r int select @r=max('+@idfield+') from '+@table1+' return@r'
EXEC (@s)
EXEC @max=exec(#temp_b)
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'mytemp' and type = 'T')
DROP TABLE mytemp
CREATE TABLE dbo.mytemp([id] INT PRIMARY KEY)
WHILE(@min <= @max)
BEGIN
INSERT INTO mytemp VALUES (@min)
@min = @min + 1
END
SET @Records = Cursor FOR
SELECT [id]
FROM mytemp
WHERE [id] not in (select @idfield from @table1)
OPEN @Records
GO
I get the following errors:
Error 156: Incorrect syntax near the keyword 'exec'
Line 13: Incorrect syntax near '#temp_a'
Incorrect syntax near the keyword 'exec'
Line 16: Incorrect syntax near '#temp_b'
Line 25: Incorrect syntax near '@min'
Must declare variable '@table1'
I've seen several examples where people execute string variables, so I don't know what the problem is. Also, @table1 is defined as a parameter, so I don't know what the problem there is either.
CREATE PROCEDURE dbo.nonsequential
@table1 varchar(25),
@idfield as varchar(25)
as
DECLARE @min int
DECLARE @max int
DECLARE @Records Cursor
DECLARE @s varchar(255)
set @s='create procedure #temp_a as declare @r int select @r=min('+@idfield+') from '+@table1+' return@r'
EXEC (@s)
EXEC @min=exec(#temp_a)
set @s='create procedure #temp_b as declare @r int select @r=max('+@idfield+') from '+@table1+' return@r'
EXEC (@s)
EXEC @max=exec(#temp_b)
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'mytemp' and type = 'T')
DROP TABLE mytemp
CREATE TABLE dbo.mytemp([id] INT PRIMARY KEY)
WHILE(@min <= @max)
BEGIN
INSERT INTO mytemp VALUES (@min)
@min = @min + 1
END
SET @Records = Cursor FOR
SELECT [id]
FROM mytemp
WHERE [id] not in (select @idfield from @table1)
OPEN @Records
GO
I get the following errors:
Error 156: Incorrect syntax near the keyword 'exec'
Line 13: Incorrect syntax near '#temp_a'
Incorrect syntax near the keyword 'exec'
Line 16: Incorrect syntax near '#temp_b'
Line 25: Incorrect syntax near '@min'
Must declare variable '@table1'
I've seen several examples where people execute string variables, so I don't know what the problem is. Also, @table1 is defined as a parameter, so I don't know what the problem there is either.