将数据从 table 插入相同的 table 作为具有新自动递增 id 的新行,使用游标逐行进行

Inserting Data from table Into Same table as a new row with new auto increment id using a cursor to go row by row

这是一个基于我的数据的示例table

我的问题:

伪代码(为清楚起见):

基本上我想复制所有内容并将其重新插入到相同的 table 但每一行都有一个新的自动递增 ID,因此就像一个新的引用 ID。 但是该行仍然具有相同的报价 ID。

为此,我的同事说我应该使用游标。我相信我的游标逻辑有些不正确,但我不确定为什么。我已经尝试过 Rubberducking 方法,但我编写的代码在逻辑上似乎是正确的。

这是我的代码:

 BEGIN TRAN

 DECLARE @OldId INT
 DECLARE @QuoteID INT
 DECLARE @NewQuoteID INT

 SET @QuoteID = 71475

 DECLARE @NewLocationID INT
 SET @NewLocationID = 0

DECLARE Location_Cursor CURSOR FOR 
     SELECT id 
     FROM tbl_Quote_Scheduled_Locations 
     WHERE Ouote_ID = @QuoteID

OPEN Location_Cursor

FETCH NEXT FROM Location_Cursor INTO @OldId

WHILE (@@FETCH_STATUS = 0)
BEGIN
    INSERT INTO tbl_Quote_Scheduled_Locations ([Account_ID], [Agent_ID],[LocationName], [Address], [City], [State], [Zip], [Ouote_id])
        SELECT 
            [Account_ID], [Agent_ID], [LocationName], [Address], [City],[State], [Zip], @QuoteID
        FROM 
            tbl_Quote_Scheduled_Locations
        WHERE 
            @QuoteID = @NewQuoteID      

    FETCH NEXT FROM Location_Cursor INTO @OldId         
END

CLOSE Location_Cursor   
DEALLOCATE Location_Cursor

--Check to see if update worked (I keep getting no value back)
SELECT s.id, s.Ouote_ID
FROM tbl_Quote_Scheduled_Locations s
WHERE @NewLocationID = SCOPE_IDENTITY()

ROLLBACK

有人可以帮助我理解为什么我的上述代码不起作用吗?

我不确定这是否与我的 INSERT 语句本身有关,或者我是否错误地创建了游标。

感谢您的帮助

这里绝对不需要那些可怕的、低效的游标之一……

只需使用简单、简单、简单的基于集合的方法:

SET @QuoteID = 71475

INSERT INTO tbl_Quote_Scheduled_Locations ([Account_ID], [Agent_ID],[LocationName], [Address], [City], [State], [Zip])
    SELECT 
        [Account_ID], [Agent_ID], [LocationName], [Address], [City],[State], [Zip]
    FROM 
        tbl_Quote_Scheduled_Locations
    WHERE 
        @QuoteID = @QuoteID;

DECLARE @NewQuoteId = SCOPE_IDENTITY();

我假设 QuoteId 是自动递增列?只是 在执行 INSERT 时不要指定 - 然后 SQL 服务器将分配一个新值。

我为其他也在为此苦苦挣扎的人提出了解决方案... Answer 从每一行插入数据并保持更新的新报价 ID。

DECLARE @QuoteId int 
SET @QuoteId = 68548
DECLARE @NewId int
DECLARE @OldId int

--Quote Table
INSERT INTO tbl_Quote (
                      [AccountId] ,[QuoteDate],[Agent_ID] ,[Rate],[From] ,[Attention],[Schedule],[Perils],[AOPDed],[WHHDed],[NSDed],[TermPermium],[AnnualPremium],[InsurerId]
                      ,[InsurerName],[SyndicateLayering],[Commission],[Subjectivity],[QuoteDocument],[Status],[Policy_ID],[CoverEffDate],[CoverExpDate],[CoveragesDays]
                      ,[StateTaxStampFee],[QuoteDocumentNotes],[Our_office_responsible_filing_evidence_of_compliance],[Our_office_responsible_filing_surplus_taxes]
                      ,[not_subject_to_surplus_line],[QuoteStatus_OID],[Firstmonths],[Scoundmonths],[Thirdmonths],[Forthmonths],[Firthmonths],[Endorsement],[Priority]
                      ,[OrgCoverEffDate],[OrgCoverExpDate],[Inter_Account_Program_Locations_ID],[Cancellation],[ReadyToBind],[AccountCert_ID],[Underwriter],[NewLocations]
                      ,[ImportedBy],[ImportedByEmail],[Renewal],[Batch],[Approved_No_changes],[Approved_With_Changes],[FirstNA],[SecoundNA],[ThirdNA],[ForthNA],[FithNA]
                      ,[Sixthmonths],[SixthNA],[Archive],[SubmissionID],[Accord],[FiveYear],[FiveYearLargeLosses],[ThreeYear],[ThreeYearLargeLosses],[NewCont],[TaxState]
                      ,[Doestheagentcontroltheaccount],[DoestheinsuredwantEarthquakeCoverage],[DoestheinsuredwantFloodCoverage],[TargetRate],[FloodSublimitRequested]
                      ,[EarthquakeSublimitRequested],[TargetAOPDeductible],[TargetWHHDeductible],[Whoistheexpiringcarrier],[Whatistheexpiringrate],[Whatistheexpiringpremium]
                      ,[Whataretheexpiringdeductibles],[AIM_QuoteID],[IncreasedBCcoverage],[IncreasedLawOrdanance],[CondoEndorement],[Sewerbackupendt],[SewerbackupendtValue]
                      ,[Winddrivenrainendt],[WinddrivenrainendtValue],[TaxcreditendtforRuralareas],[Optionaltenantdiscriminationquote],[NoKnownLossLetterattached]
                      ,[StratatoquotesubjectNoKnownLossLetter],[ControlingCityMunicipality],[ControlingCountyMunicipality],[Status_ID],[SubStatus_ID],[InspectionContact]
                      ,[InspectionEmail],[InspectionPhone],[Login_ID],[NeedByDate],[CustomerID],[Type],[Customer],[BrokerName],[BrokerID],[DecCertNumber],[ORGSubmissionID]
                      ,[CancelType],[OrgQuoteID],[Ver],[Arcive],[BrokerQuoteStatus],[GLQuoteID],[GLQuote],[FlatEndorsement],[MarkedReadyToQuote],[UnderwriterID]
                       )


    SELECT [AccountId] ,[QuoteDate],[Agent_ID] ,[Rate],[From] ,[Attention],[Schedule],[Perils],[AOPDed],[WHHDed],[NSDed],[TermPermium],[AnnualPremium],[InsurerId]
                      ,[InsurerName],[SyndicateLayering],[Commission],[Subjectivity],[QuoteDocument],[Status],[Policy_ID],[CoverEffDate],[CoverExpDate],[CoveragesDays]
                      ,[StateTaxStampFee],[QuoteDocumentNotes],[Our_office_responsible_filing_evidence_of_compliance],[Our_office_responsible_filing_surplus_taxes]
                      ,[not_subject_to_surplus_line],[QuoteStatus_OID],[Firstmonths],[Scoundmonths],[Thirdmonths],[Forthmonths],[Firthmonths],[Endorsement],[Priority]
                      ,[OrgCoverEffDate],[OrgCoverExpDate],[Inter_Account_Program_Locations_ID],[Cancellation],[ReadyToBind],[AccountCert_ID],[Underwriter],[NewLocations]
                      ,[ImportedBy],[ImportedByEmail],[Renewal],[Batch],[Approved_No_changes],[Approved_With_Changes],[FirstNA],[SecoundNA],[ThirdNA],[ForthNA],[FithNA]
                      ,[Sixthmonths],[SixthNA],[Archive],[SubmissionID],[Accord],[FiveYear],[FiveYearLargeLosses],[ThreeYear],[ThreeYearLargeLosses],[NewCont],[TaxState]
                      ,[Doestheagentcontroltheaccount],[DoestheinsuredwantEarthquakeCoverage],[DoestheinsuredwantFloodCoverage],[TargetRate],[FloodSublimitRequested]
                      ,[EarthquakeSublimitRequested],[TargetAOPDeductible],[TargetWHHDeductible],[Whoistheexpiringcarrier],[Whatistheexpiringrate],[Whatistheexpiringpremium]
                      ,[Whataretheexpiringdeductibles],[AIM_QuoteID],[IncreasedBCcoverage],[IncreasedLawOrdanance],[CondoEndorement],[Sewerbackupendt],[SewerbackupendtValue]
                      ,[Winddrivenrainendt],[WinddrivenrainendtValue],[TaxcreditendtforRuralareas],[Optionaltenantdiscriminationquote],[NoKnownLossLetterattached]
                      ,[StratatoquotesubjectNoKnownLossLetter],[ControlingCityMunicipality],[ControlingCountyMunicipality],[Status_ID],[SubStatus_ID],[InspectionContact]
                      ,[InspectionEmail],[InspectionPhone],[Login_ID],[NeedByDate],[CustomerID],[Type],[Customer],[BrokerName],[BrokerID],[DecCertNumber],[ORGSubmissionID]
                      ,[CancelType],[OrgQuoteID],[Ver],[Arcive],[BrokerQuoteStatus],[GLQuoteID],[GLQuote],[FlatEndorsement],[MarkedReadyToQuote],[UnderwriterID]

    FROM tbl_Quote
    WHERE ID = @QuoteID


UPDATE tbl_Quote SET [QuoteDate] = GETDATE()
WHERE Id = SCOPE_IDENTITY()


SET @NewId = SCOPE_IDENTITY()

SELECT * FROM tbl_Quote
WHERE id = @NewId


BEGIN TRAN
--Locations Cursor for Tbl_Quote_Scheduled_Locations
DECLARE Location_Cursor CURSOR

FOR SELECT id from tbl_Quote_Scheduled_Locations WHERE Ouote_ID = @QuoteId

OPEN Location_Cursor
FETCH NEXT FROM Location_Cursor INTO
@OldId
WHILE (@@FETCH_STATUS = 0)
    BEGIN
            INSERT INTO tbl_Quote_Scheduled_Locations 
            ([Account_ID],[Agent_ID],[LocationName],[Address],[City],[State],[Zip],[County],[Units],[Pools],[OccupancyPercentage],[YOC]
                                              ,[ConstructionType],[Wiring],[NoOfBuildings],[Stories],[RoofAge],[Area],[Section8],[SmokeDetectors],[A_S],[Amt_Bldgs]
                                              ,[Amt_Rents],[Amt_Cnts],[Amt_Other],[Status],[cStatus],[Latitude],[Longitude],[LastChangeDate],[LastChangeUserID]
                                              ,[LocationDeductable],[Name],[Policy],[Program],[Tier],[ORG_ID],[Policy_ID],[DeclinedToQuote],Ouote_ID,[Rate]
                                              ,[tbl_Scheduled_Locations_OID],[Days],[Premium],[EffDate],[WHH],[AOP],[NotTaxableSubTotal],[NotTaxableSubTotal2]
                                              ,[TaxableSubtotal],[StateTax],[Stamping_Fee],[Grand_Total],[Scheduled_Locations_ID],[Bind_ID],[Bind_Date],[CoverageEffDate]
                                              ,[CoverageExpDate],[ReadyToBind],[ProductId],[ProductName],[NonTaxB_M_Factor],[NonTax2_Factor],[PolicyMultiplyer_Factor]
                                              ,[StateTax_Factor],[Stamping_Fee_Factor],[TIV],[Void],[CommissionRate],[Bound],[ProcessReason]
                                              ,[DaysPerYear],[AccountCert_ID],[ITV],[Cancellation],[ProFactor],[DedPerBldg],[DedNote],[OrgAddress],[NewLocation]
                                              ,[InspectionFlag],[InspectionFee],[InspectionFeeStateTax],[InspectionStamping_Fee],[Archive],[Earthquake],[Flood]
                                              ,[Region],[SubmissionDetailID],[SubmissionID],[Error],[PrimaryAddress],[ErrorCount],[GeoCode],[ORGLocationID]
                                              ,[GlLocationId],[MatrixRate])

            SELECT 
            [Account_ID],[Agent_ID],[LocationName],[Address],[City],[State],[Zip],[County],[Units],[Pools],[OccupancyPercentage],[YOC]
                                              ,[ConstructionType],[Wiring],[NoOfBuildings],[Stories],[RoofAge],[Area],[Section8],[SmokeDetectors],[A_S],[Amt_Bldgs]
                                              ,[Amt_Rents],[Amt_Cnts],[Amt_Other],[Status],[cStatus],[Latitude],[Longitude],[LastChangeDate],[LastChangeUserID]
                                              ,[LocationDeductable],[Name],[Policy],[Program],[Tier],[ORG_ID],[Policy_ID],[DeclinedToQuote],@NewId,[Rate]
                                              ,[tbl_Scheduled_Locations_OID],[Days],[Premium],[EffDate],[WHH],[AOP],[NotTaxableSubTotal],[NotTaxableSubTotal2]
                                              ,[TaxableSubtotal],[StateTax],[Stamping_Fee],[Grand_Total],[Scheduled_Locations_ID],[Bind_ID],[Bind_Date],[CoverageEffDate]
                                              ,[CoverageExpDate],[ReadyToBind],[ProductId],[ProductName],[NonTaxB_M_Factor],[NonTax2_Factor],[PolicyMultiplyer_Factor]
                                              ,[StateTax_Factor],[Stamping_Fee_Factor],[TIV],[Void],[CommissionRate],[Bound],[ProcessReason]
                                              ,[DaysPerYear],[AccountCert_ID],[ITV],[Cancellation],[ProFactor],[DedPerBldg],[DedNote],[OrgAddress],[NewLocation]
                                              ,[InspectionFlag],[InspectionFee],[InspectionFeeStateTax],[InspectionStamping_Fee],[Archive],[Earthquake],[Flood]
                                              ,[Region],[SubmissionDetailID],[SubmissionID],[Error],[PrimaryAddress],[ErrorCount],[GeoCode],[ORGLocationID]
                                              ,[GlLocationId],[MatrixRate]
            FROM tbl_Quote_Scheduled_Locations
            WHERE id = @OldId AND Ouote_ID = @QuoteId

            FETCH NEXT FROM Location_Cursor INTO
            @OldId
    END

CLOSE Location_Cursor   
DEALLOCATE Location_Cursor

SELECT * FROM tbl_Quote_Scheduled_Locations
WHERE Ouote_ID = @QuoteId

SELECT * FROM tbl_Quote_Scheduled_Locations
WHERE Ouote_ID = @NewId


COMMIT