简体   繁体   中英

Insertion of records based on some condition

I'm trying to insert few records from the temporary table using a SQL Server stored procedure. There is a percentage column in the temporary table and a PQ number column. In a table there may exists more than 1 row with the same PQ number. But for insertion to happen the sum of percentage for the same PQ number should be 100%. I couldn't write the where clause for this situation.

CREATE PROCEDURE [dbo].[Upsert_DebitSheet]
    @filename VARCHAR(250)
AS
BEGIN
    SET XACT_ABORT ON 

    RETRY: -- Label RETRY

    BEGIN TRANSACTION
    BEGIN TRY
        SET NOCOUNT ON;

        INSERT INTO [dbo].[DebitSheet]([Date], [RMMName], [Invoice],[PQNumber], [CAF],
                                       [Percentage], [Amount], [FileName])
            SELECT 
                *, @filename 
            FROM
                (SELECT 
                     [Date], [RMMName], [Invoice], [PQNumber], [CAF],
                     [Percentage], [Amount]
                 FROM 
                     [dbo].[TempDebitSheet]
                 WHERE) result

        SELECT @@ROWCOUNT

        TRUNCATE TABLE [dbo].[TempDebitSheet]

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        PRINT ERROR_MESSAGE()
        ROLLBACK TRANSACTION

        IF ERROR_NUMBER() = 1205 -- Deadlock Error Number
        BEGIN
            WAITFOR DELAY '00:00:00.05' -- Wait for 5 ms
            GOTO RETRY -- Go to Label RETRY
        END
    END CATCH

    SET ROWCOUNT 0;
END

Temporary Table

MainTable(Expected Result)

You can use subquery in the WHERE

INSERT INTO [dbo].[DebitSheet]
   ([Date]
   ,[RMMName]
   ,[Invoice]
   ,[PQNumber]
   ,[CAF]          
   ,[Percentage]
   ,[Amount]
   ,[FileName])
SELECT [Date]
   ,[RMMName]
   ,[Invoice]
   ,[PQNumber]
   ,[CAF]          
   ,[Percentage]
   ,[Amount]
FROM [dbo].[TempDebitSheet]
WHERE EXISTS (
    SELECT tmp.[PQNumber] 
    FROM [dbo].[TempDebitSheet] tmp
    WHERE tmp.[PQNumber] = [TempDebitSheet].[PQNumber]
    GROUP BY tmp.[PQNumber]
    HAVING SUM(tmp.[Percentage]) = 100       
)

像这样修改查询插入到...选择结果。*,@文件名来自(....)结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM