Установка нескольких переменных из CTE - PullRequest
0 голосов
/ 20 апреля 2020
 SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER dbo.transferVehicle
ON dbo.Vehicles
AFTER INSERT 
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @Level0Key INT, @Level1Key INT, @Level2Key INT, @Level3Key INT, @Level4Key INT, @Level5Key INT,@Level6Key INT,@Level7Key INT, @LocKey INT;

    SELECT @LocKey = [LocKey] FROM Inserted ;

        with tbParent as
(
    select * from Canepro.dbo.locations where LocKey= @LocKey
    union all
    select locations.* from Canepro.dbo.locations  join tbParent  on locations.LocKey = tbParent.ParentKey
),

    tbsons as
(
    select * from Canepro.dbo.locations where LocKey= @LocKey
    union all
    select locations.* from Canepro.dbo.locations  join tbsons  on locations.ParentKey= tbsons.LocKey
),
    tball as
(
    select * from  tbParent as p
    union 
    select * from tbsons as s

),
final as
(
select number = ROW_NUMBER() OVER (ORDER BY t.LocKey), t.LocKey,t.LocName ,  t.ParentKey 
from tball as t 
)

    SELECT @Level1Key = LocKey from final where number = 1 
    SELECT @Level2Key = LocKey from final where number = 2 -- wont pick up 'final' from this select 
    SELECT @Level3Key = LocKey from final where number = 3
    SELECT @Level4Key = LocKey from final where number = 4


    INSERT INTO [NewDatabase].dbo.Vehicles (VehCode, VehicleNumber, RegistrationNumber, Description, FuelKey, CatKey, Active, ExpectedConsumption, IsPetrol, LicenseExpiryDate, FuelTankCapacity, OdometerReading, Level0LocKey, Level1LocKey, Level2LocKey,Level3LocKey, Level4LocKey, Level5LocKey, Level6LocKey, Level7Key)

        SELECT 
            VehCode, VehicleNumber, RegistrationNumber, Description, FuelType, CatKey, Active, ExpectedConsumption, IsPetrol, LicenseExpiryDate, FuelTankCapacity, OdometerReading, LocKey, @Level0Key, @Level1Key, @Level2Key, @Level3Key, @Level4Key, @Level5Key, @Level6Key, @Level7Key -- then all the other nodes that relate to the lockey, above and below is level from level0 (The top of the tree) to level 6 of the tree
        FROM   
            inserted;
END
GO

Я создал этот триггер, который берет любой заданный узел в древовидной структуре, а затем добавляет себя со всеми дочерними и родительскими узлами в таблицу CTE с именем final.

Вы увидите, что у меня есть несколько объявлений переменных например. "Level1key"

Я хочу SET / SELECT каждой строки в 'final' в соответствующую ей переменную EG.

"SELECT @Level1Key = LocKey from final where number = 1"  
"SELECT @Level2Key = LocKey from final where number = 2"  
"SELECT @Level3Key = LocKey from final where number = 3"  

Однако он не поднимает мою таблицу CTE 'final' после первого выбора.

Ниже приведена фотография ошибки Проблема Проблема

Причина, по которой я пытался использовать несколько операторов Select в CTE, заключается в попытке изобразить, что мне нужно использовать несколько указанных c операторов WHERE, в основном я ищу способ достижения той же логики c, однако, в одном операторе SELECT (в котором доступен CTE)

Заранее спасибо

...