mercredi 15 septembre 2021

IF Condition Returning too Many Values

I am pretty new to the t-sql world and am trying to create a query that will change a value based on multiple criteria.

TSH1 is the main table that values will be changed in. Freightview is the table that has the shipping amount I need to add into TSH1.

I want the query to look for matches between the tables and when there is one make a change to the FREIGHT line if it exists. If the FREIGHT line doesn't exist then it needs to add a line with the invoice amount from Freightview table.

My issue is the IF statement. It is returning two many values for the query to work. What do I need to change?

The last two queries are to return values that are not in each table.

SELECT *
FROM TSH1 T 
JOIN Freightview FR on FR.[Shippers number] = T.sonum
IF
    ((SELECT [Shippers number] FROM Freightview) = (SELECT sonum FROM TSH1 T WHERE EXISTS(SELECT * FROM TSH1 T WHERE T.productnum = 'FRT-OUT' OR T.productnum = 'FRT-IN' OR T.productnum = 'FRT')))
    
     
    BEGIN
    UPDATE TSH1 SET tcost = FR.[Invoice Amount] FROM TSH1 T INNER JOIN Freightview FR on FR.[Shippers number] = T.sonum 
    WHERE T.productnum = 'FRT-OUT' OR T.productnum = 'FRT-IN' OR T.productnum = 'FRT';
    END

    ELSE IF
    ((SELECT [Shippers number] FROM Freightview) = (SELECT sonum FROM TSH1 T WHERE NOT EXISTS(SELECT * FROM TSH1 T WHERE T.productnum = 'FRT-OUT' OR T.productnum = 'FRT-IN' OR T.productnum = 'FRT')))
    
    
    BEGIN
    SELECT *  INTO temp_table FROM TSH1 T INNER JOIN Freightview FR on FR.[Shippers number] = T.sonum
    WHERE FR.[Shippers number] = T.sonum AND NOT EXISTS (SELECT productnum from TSH1 T where T.productnum = 'FRT-OUT' OR T.productnum = 'FRT-IN' OR T.productnum = 'FRT');
    UPDATE temp_table SET temp_table.productnum = 'FRT', [Invoice Amount] = TT.tcost, temp_table.productid = '7240', temp_table.pd = 'FREIGHT', temp_table.qtyfulfilled = 1, 
    temp_table.tprice = 0, temp_table.stdcost = 0, temp_table.flag = 'D', temp_table.avgcost = NULL
    FROM temp_table TT 
    INNER JOIN Freightview FR on TT.sonum = FR.[Shippers number];
    UPDATE temp_table SET ID=NULL;
    DELETE x FROM (
    SELECT *, rn=row_number() over (partition by TT.sonum order by TT.soid)
    FROM temp_table TT
        ) x
    WHERE rn > 1;
    INSERT INTO TSH1 SELECT * FROM temp_table;
    DROP TABLE temp_table;
    END
    ELSE 
    BEGIN
    SELECT * 
    FROM TSH1 T 
    LEFT JOIN Freightview FR on T.sonum = FR.[Shippers number]
    WHERE FR.[Shippers number] IS NULL;
    END

    BEGIN
    SELECT * 
    FROM Freightview FR 
    LEFT JOIN TSH1_Backup T on T.sonum = FR.[Shippers number]
    WHERE T.sonum IS NULL;
    END

END```


Aucun commentaire:

Enregistrer un commentaire