sql-server – 如何在SQL Server中编写foreach?

前端之家收集整理的这篇文章主要介绍了sql-server – 如何在SQL Server中编写foreach?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在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
原文链接:https://www.f2er.com/mssql/83694.html

猜你在找的MsSQL相关文章