根据某些条件插入记录

时间:2016-08-04 05:02:40

标签: sql sql-server sql-server-2008 sql-server-2012 sql-server-2014

我尝试使用SQL Server存储过程从临时表中插入一些记录。临时表中有一个百分比列和一个PQ编号列。在表中,可能存在多于一行且具有相同PQ编号的行。但是对于插入发生,相同PQ编号的百分比之和应为100%。我无法为这种情况编写where子句。

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)

2 个答案:

答案 0 :(得分:2)

您可以在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       
)

答案 1 :(得分:0)

像这样修改您的查询 插入 ... 从(....)结果

中选择结果。*,@ filename