加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程 > 正文

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

发布时间:2021-01-20 14:02:40 所属栏目:编程 来源:网络整理
导读:我试图在for-each中实现某些对象,我想在个中获取返回的select语句的ID并行使它们中的每一个. DECLARE @i intDECLARE @PractitionerId intDECLARE @numrows intDECLARE @Practitioner TABLE ( idx smallint Primary Key IDENTITY(1,1),PractitionerId int)INSE

我试图在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

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读