Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL Stored Procedure Cursor help needed please 1

Status
Not open for further replies.

tamathaltarak

Programmer
May 2, 2002
3
GB
Hi,

Can someone please help me and show me where I am going wrong with this.

I am creating a stored procedure that uses a cursor to execute an insert statement. What I can't seem to do is pass parameters to the cursor.
I end up with invalid object @sTable. Any ideas ???


Code:
CREATE PROCEDURE SP_MYPROCEDURE (@sTable SYSNAME) AS
DECLARE @x	INT
DECLARE @y	INT
DECLARE @z	INT

DECLARE my_cursor CURSOR FOR
	SELECT x, y, z FROM @sTable
OPEN my_cursor

FETCH NEXT FROM my_cursor INTO @x, @y, @z
WHILE (@@FETCH_STATUS <> -1)
BEGIN
	IF (@@FETCH_STATUS <> -2)
		
		INSERT INTO MyTable (x, y, z)
		VALUES (@x, @y, @z)
		
	FETCH NEXT FROM my_cursor INTO @x, @y, @z
END
CLOSE my_cursor

DEALLOCATE my_cursor
GO

Any help will be really appreciated.

Thanks in advance :-;

Tamath Altarak
 
Dear Tamath,

I have no SQL-Server running, so I cannot figure it out but i assume:

could be your parameter is passed as a varchar and cannot be converted into sysname properly or has leading or trailing spaces.

HTH

regards

Astrid
 
You cannot use variables for object or column names in SQL Server. You must create and execute dynamic SQL.

CREATE PROCEDURE SP_MYPROCEDURE (@sTable SYSNAME) AS
DECLARE @x INT
DECLARE @y INT
DECLARE @z INT
DECLARE @sql varchar(200)

Set @sql='DECLARE my_cursor CURSOR FOR SELECT x, y, z FROM ' + @sTable

Exec(@sql)


OPEN my_cursor
.
.
. Terry L. Broadbent - DBA
Computing Links:
faq183-874 contains &quot;Suggestions for Getting Quick and Appropriate Answers&quot; to your questions.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top