【问题标题】:How to store record into a declared variable for later use in the query?如何将记录存储到声明的变量中以供以后在查询中使用?
【发布时间】:2022-08-12 22:09:22
【问题描述】:

有 3 个表相互关联,所以我不能只删除行。

我编写了一个声明记录的查询,遍历第一个表,然后使用 _id 获取第二个表的记录,然后是第三个表。

但是在从每个表中获取所有 id 后,我需要从第 3 个表中删除这些 id,然后是第 2 个表,然后是第 1 个表。

我无法声明并将找到的行存储到变量中。

DO $$
    DECLARE
        firstTableRecord record;
        -- tried to declare something like
        -- firstTableRecord record[]; or firstTableRecord [];

        secondTableRecord record;
        thirdTableRecord record;

    BEGIN
        -- Get FirstTable Records
        FOR firstTableRecord IN
            SELECT _id FROM public.\"FirstTable\"
            LOOP
                RAISE NOTICE \'firstTableRecord: %\', firstTableRecord;

                -- Using the Ids from FirstTable get records from SecondTable
                FOR secondTableRecord IN
                    select _id from public.\"SecondTable\" where _id = firstTableRecord._id
                    LOOP
                        RAISE NOTICE \'secondTableRecord: %\', secondTableRecord;

                        -- Using the Ids from SecondTable get records from ThirdTable
                        FOR thirdTableRecord IN
                            select _id from public.\"ThirdTable\" where _id = firstTableRecord._id
                            LOOP
                                RAISE NOTICE \'thirdTableRecord: %\', thirdTableRecord;
                            END LOOP;
                    END LOOP;
            END LOOP;

        -- remove all record found in third table
        -- remove all record found in second table
        -- remove all record found in first table

    END$$;

我是否认为/这样做是错误的方向,即有一种更简单的方法或如何做到这一点?

提前感谢您的任何建议和意见;

标签: sql postgresql


【解决方案1】:

我不是 SQL 专家,但在四处寻找答案后,我想出了使用 Cursors 的方法。这有点麻烦,我不确定它在大型记录集上的性能如何,但这可能会奏效:

DECLARE @MyCursor CURSOR;
DECLARE @Field1 int;
DECLARE @Field2 int;
DECLARE @Field3 int;
DECLARE @Field4 int;
DECLARE @Field5 uniqueidentifier;

BEGIN
    SET @MyCursor = CURSOR FOR
    SELECT Field1, Field2, Field3, Field4, Field5
        From <your tables with any necessary joins and or sorting>
    OPEN @MyCursor 
    FETCH NEXT FROM @MyCursor INTO 
        @Field1, @Field2, @Field3, @Field4, @Field5
    WHILE @@FETCH_STATUS = 0
    BEGIN
        -- your loop code --
        Print char(10) + N'Field1:' + Cast(@Field1 as nvarchar(50));

        FETCH NEXT FROM @MyCursor INTO 
            @Field1, @Field2, @Field3, @Field4, @Field5
    END; 
    CLOSE @MyCursor ;
    DEALLOCATE @MyCursor;
End

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2021-10-11
    • 2013-08-27
    • 2017-12-10
    相关资源
    最近更新 更多