Thimo Franken
Thimo Franken

Reputation: 330

Getting multiple columns selected into variables

I am having problems with the following code:

/* Cursor */
DECLARE @RelationCursor CURSOR 
SET @RelationCursor = (SELECT [fms].[dbo].[Relation].[RELATIONCODE], [fms].[dbo].[Relation].[COMPANYNAME] INTO @RelationCode, @CompanyName FROM [fms].[dbo].[Relation])

OPEN @RelationCursor
FETCH NEXT FROM @RelationCursor INTO @RelationCode, @CompanyName

WHILE @@FETCH_STATUS = 0
BEGIN
    print(@RelationCode)
    print(@CompanyName)

    FETCH NEXT FROM @RelationCursor INTO @RelationCode, @CompanyName
END

CLOSE @RelationCursor

I am trying to get RelationCode and Companyname into @RelationCode and @Companyname so I can use them in the cursor loop. But I get an error in the SELECT query:

Msg 156, Level 15, State 1, Procedure spLoadProfits, Line 21
Incorrect syntax near the keyword 'INTO'.

But the query seems completely fine to me and I can't seem to figure out the problem about this. Does anyone have an idea on how to fix this?

Upvotes: 0

Views: 44

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82474

A cursor name should not start with @, and also you need to deallocate the cursor when you are done with it.

Try this instead:

DECLARE @RelationCode int,  -- I guessed the data type, change if needed
        @CompanyName varchar(100)  -- I guessed the data type, change if needed

DECLARE RelationCursor CURSOR FOR 
    SELECT [fms].[dbo].[Relation].[RELATIONCODE], [fms].[dbo].[Relation].[COMPANYNAME] 
    FROM [fms].[dbo].[Relation]

OPEN RelationCursor

FETCH NEXT FROM RelationCursor INTO @RelationCode, @CompanyName

WHILE @@FETCH_STATUS = 0
BEGIN
    print(@RelationCode)
    print(@CompanyName)

    FETCH NEXT FROM RelationCursor INTO @RelationCode, @CompanyName
END

CLOSE RelationCursor
DEALLOCATE RelationCursor;  

Upvotes: 2

Related Questions