我正在尝试实现类似于 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
关于sql-server - 如何在 SQL Server 中编写 foreach?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18513986/