我试图在for-each中实现某些东西,我想在其中获取返回的select语句的ID并使用它们中的每一个.
DECLARE @i int DECLARE @PractitionerId int DECLARE @numrows int DECLARE @Practitioner TABLE ( idx smallint Primary Key IDENTITY(1,1),PractitionerId int ) INSERT @Practitioner SELECT distinct PractitionerId FROM Practitioner SET @i = 1 SET @numrows = (SELECT COUNT(*) FROM Practitioner) IF @numrows > 0 WHILE (@i <= (SELECT MAX(idx) FROM Practitioner)) BEGIN SET @PractitionerId = (SELECT PractitionerId FROM @Practitioner WHERE idx = @i) --Do something with Id here PRINT @PractitionerId SET @i = @i + 1 END
目前我有一些看起来像上面的东西,但我得到错误:
Invalid column name ‘idx’.
可能有人
解决方法
你似乎想要使用CURSOR.虽然大多数情况下最好使用基于集合的解决方案,但有时候CURSOR是最佳解决方案.在不了解您的真实问题的情况下,我们无法帮助您:
DECLARE @PractitionerId int DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR SELECT DISTINCT PractitionerId FROM Practitioner OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO @PractitionerId WHILE @@FETCH_STATUS = 0 BEGIN --Do something with Id here PRINT @PractitionerId FETCH NEXT FROM MY_CURSOR INTO @PractitionerId END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR