我有一个使用 Oracle 数据库编写的过程,现在我想将它迁移到 SQL Server,但在循环方面遇到了问题。据我所知,SQL Server 没有“FOR”循环,它只有“WHILE”循环。代码是:
FOR something in columns LOOP PRINT('SOMETHING'); PRINT('SOMETHING'); END LOOP;
我想将其转换为 SQL Server 语法,但在涉及 MS SQL 语法时我遇到了问题。
您可以使用光标:
DECLARE @col_name VARCHAR(128); DECLARE @col_value VARCHAR(128); -- declare cursor DECLARE columns CURSOR FOR SELECT something, other_thing FROM table_list; -- open cursor OPEN columns; -- loop through a cursor FETCH NEXT FROM columns INTO @col_name, @col_value; WHILE @@FETCH_STATUS = 0 BEGIN PRINT CONCAT('SOMETHING: ', @col_name, ' / OTHER_THING: ', @col_value); FETCH NEXT FROM columns INTO @col_name, @col_value; END; -- close and deallocate cursor CLOSE columns ; DEALLOCATE columns;