将多个列选入变量

时间:2016-12-29 10:04:44

标签: sql-server tsql

我遇到以下代码问题:

/* 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

我正在尝试将RelationCodeCompanyname转换为@RelationCode@Companyname,以便我可以在游标循环中使用它们。但是我在SELECT查询中收到错误:

  

Msg 156,Level 15,State 1,Procedure spLoadProfits,Line 21
  关键字' INTO'附近的语法不正确。

但查询对我来说似乎完全没问题,我似乎无法弄清楚这个问题。有没有人知道如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

游标名称不应以@开头,并且您还需要在完成游标后取消分配游标。

请改为尝试:

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;