I need to rewrite this so it does not cause an overrun on my db. I need to rewrite it so it does not use a cursor.
Thank you.
UPDATED Here's some test data:
CREATE TABLE #TableB(SKU INT, BeginYear INT, EndYear INT, OptionA VARCHAR(10), OptionB VARCHAR(10))
INSERT INTO #TableB(SKU, BeginYear, EndYear, OptionA, OptionB)
VALUES (1, 1920, 1950, 'option1', 'option1'),
(1, 1980, 2001, 'option1', 'option2'),
(1, 1940, 1952, 'option1', 'option1'), --overlapping years
(2, 2001, 2005, 'option1', 'option1')
CREATE TABLE #TableA(SKU INT, OptionA VARCHAR(10), OptionB VARCHAR(10), Years INT)
Then you can try a recursive CTE:
;WITH CTE AS
(
SELECT DISTINCT SKU, BeginYear, EndYear, OptionA, OptionB
FROM #TableB
UNION ALL
SELECT SKU, BeginYear+1, EndYear, OptionA, OptionB
FROM CTE
WHERE BeginYear < EndYear
)
INSERT INTO #TableA(SKU, OptionA, OptionB, Years)
SELECT DISTINCT SKU, OptionA, OptionB, BeginYear
FROM CTE
OPTION(MAXRECURSION 0)
SELECT *
FROM #TableA
ORDER BY SKU, OptionA, OptionB, Years
Here there's no cartesian product.
You can easily substitute a while loop for a cursor and if you are blowing out your tempdb then do some intermediate transactions
declare #counter int
declare #temptable as tatble (RecID int Identity(1,1),
SKU Varchar(25),
OptionA Varchar(50),
OptionB Varchar(50),
CurrentYear Int,
EndYear Int)
insert into #temptable
Select SKU,OptionA, OptionB, BeginYear,EndYear
From TableB
set #counter = (select max(recid) from #temptable)
begin transaction
while #counter <> 0
Begin
(***whatever sql logic***)
if (#counter % 5000 = 0) and ##error = 0
commit Transaction
begin Transaction
set #counter = #counter -1
End
commit transaction
May be use less number of times the insert happen
Declare #temp table (
SKU Varchar(25),
OptionA Varchar(50),
OptionB Varchar(50),
[Year] Int
)
While ##FETCH_STATUS = 0
Begin
While #CurrentYear <= #EndYear
Begin
Insert Into #temp(SKU, OptionA, OptionB, Years)
Values(#SKU, #OptionA, #OptionB, #CurrentYear)
Set #CurrentYear = #CurrentYear + 1
End
Insert Into TableA
Select * From #temp
Delete From #temp
Fetch Next From #Row Into #SKU, #CurrentYear, #EndYear, #OptionA, #OptionB
End
Related
I need to calculate sum of past six rows for same day for given id.
Have a look at the sample data and result expected..
create table #t (id int, a datetime, dy varchar(10), t int);
insert into #t values
(1,'2017-01-03','Tuesday',7),
(1,'2017-01-10','Tuesday',5),
(1,'2017-01-17','Tuesday',5),
(1,'2017-01-24','Tuesday',2),
(1,'2017-01-31','Tuesday',6),
(1,'2017-02-07','Tuesday',4),
(1,'2017-02-14','Tuesday',5),
(1,'2017-02-21','Monday',2),
(1,'2017-02-28','Monday',4),
(1,'2017-03-07','Monday',4),
(1,'2017-03-17','Monday',4),
(1,'2017-03-21','Monday',4);
(1,'2017-03-2','Monday',4);
create table #t_result (id int, a datetime, dy varchar(10),t int);
insert into #t_result values
(1,'2017-01-03','Tuesday',29),
(1,'2017-02-14','Monday',22)
select * from #t
select * from #t_result
Thanks in advance
You can do some window function manipulation and output every 6th row (modulo operator on ROW_NUMBER).
SELECT
id, a, [sum]
FROM
(
SELECT
id
, FIRST_VALUE( a ) OVER (ORDER BY a ROWS 5 PRECEDING) AS a
, SUM( t ) OVER (ORDER BY a ROWS 5 PRECEDING) AS [sum]
, ROW_NUMBER() OVER (ORDER BY a) AS rownum
FROM
#t
) AS data
WHERE
rownum % 6 = 0
--Try Using While Loop
BEGIN TRAN
CREATE TABLE #t (id INT, a DATETIME ,dy VARCHAR(10), t INT);
CREATE TABLE #t_result (id INT, a DATETIME,dy VARCHAR(10),t INT);
CREATE TABLE #Temp (id INT, a DATETIME, t INT, dy VARCHAR(10),temp_count INT);
INSERT INTO #T VALUES
(1,'2017-01-03','Thursday',7),
(1,'2017-01-10','Thursday',5),
(1,'2017-01-17','Thursday',5),
(1,'2017-01-24','Thursday',2),
(1,'2017-01-31','Thursday',6),
(1,'2017-02-07','Thursday',4),
(1,'2017-02-14','Thursday',5),
(1,'2017-02-21','Monday',2),
(1,'2017-02-28','Monday',4),
(1,'2017-03-07','Monday',4),
(1,'2017-03-17','Monday',4),
(1,'2017-03-21','Monday',4),
(1,'2017-03-2' ,'Monday',4)
DECLARE #Strt INT,#End INT
SELECT *, ROW_NUMBER()OVER(ORDER BY ID)rownum INTO #Temp_data FROM #t
SET #Strt=1
SELECT #End= MAX(rownum) FROM #Temp_data
WHILE #Strt<= #End BEGIN
DECLARE #Id INT , #T INT , #Date DATETIME, #total INT, #count INT, #Temp_count INT, #D DATETIME, #Dy VARCHAR(10)
SELECT #Id= Id, #T=t, #Dy=dy, #Date= a FROM #Temp_data WHERE rownum= #Strt
INSERT INTO #Temp
SELECT #Id, #Date, #T, #Dy,1
SELECT #Temp_count= COUNT(*) FROM #Temp
IF #Temp_count=6 BEGIN
SELECT *,ROW_NUMBER()OVER(Order by ID)rownum INTO #tt FROM #Temp
SELECT #D=a FROM #tt WHERE rownum=1
INSERT INTO #t_result
SELECT ID, #D,dy,SUM(t)
FROM #Temp
WHERE DATEPART(yyyy, a) = YEAR(DATEADD(year,-1,GETDATE()))AND dy = DATENAME(DW,GETDATE())
GROUP BY id,dy
HAVING COUNT(*)=6
DELETE FROM #Temp
DROP TABLE #tt
END
SET #Strt= #Strt +1
END
SELECT * FROM #t_result
ROLLBACK TRAN
Try this:
SELECT MIN(D.id)Id,MIN(D.a)a,D.dy,SUM(D.t)T
FROM(
select *,ROW_NUMBER() OVER(PARTITION BY id,dy ORDER BY a)RN
from #t
)D
WHERE D.RN<=6
GROUP BY D.dy
ORDER BY a
OutPut:
Id a dy T
1 2017-01-03 00:00:00.000 Tuesday 29
1 2017-02-21 00:00:00.000 Monday 22
Let's say I have a booking covering 6 hours and 3 discounts covering 2 hours each. I want to split my booking into 3 parts so I can allocate 2 hours per discount.
It would return something like this:
BookingId 1 | DiscountId 1 | Qty 2
BookingId 1 | DiscountId 2 | Qty 2
BookingId 1 | DiscountId 3 | Qty 2
I would then insert those records this into another table.
I'm using an heavily optimized query to determine the number of hours available for each discount. However, I can't find a "good" way to allocate my booking to each discount without using a cursor.
(...)
WHILE ##FETCH_STATUS = 0
BEGIN
IF #RequiredQty = 0
RETURN
IF #RequiredQty <= #AvailableQty
BEGIN
INSERT INTO discount.Usage (DiscountId, BookingId, Quantity)
VALUES (#DiscountId, #BookingId, #RequiredQty)
SET #RequiredQty = 0
END
IF #RequiredQty > #AvailableQty
BEGIN
INSERT INTO discount.Usage (DiscountId, BookingId, Quantity)
VALUES (#DiscountId, #BookingId, #AvailableQty)
SET #RequiredQty -= #AvailableQty
END
FETCH NEXT FROM ecursor INTO #DiscountId, #AvailableQty
END
DEALLOCATE ecursor
I tried building the corresponding query but I can't select and assign variables at the same time. Using a cursor is not really a problem (besides some potential performance issues) but I was just curious to see if with the newest SQL Server we can convert our old cursors to something better?
Thanks,
Seb
You can useCTE RECURSIVE to make a Table.
like this.
DECLARE #BookingId INT = 1;
DECLARE #RequiredQty INT = 2;
DECLARE #Hours INT = 7;
CREATE TABLE #T
(
BookingId INT,
DiscountId INT,
Quantity INT
)
;WITH CTE([Count],[Quantity],Rk) AS
(
SELECT
CASE
WHEN [HOURS] - #RequiredQty > #RequiredQty THEN #RequiredQty
ELSE [HOURS] - #RequiredQty
END ,
T.HOURS,1
FROM
(
SELECT #Hours [HOURS]
) AS T
UNION ALL
SELECT CASE
WHEN CTE.[Quantity] - #RequiredQty > #RequiredQty THEN #RequiredQty
ELSE CTE.[Quantity] - #RequiredQty
END AS [Count],
CTE.[Quantity] - #RequiredQty,
RK + 1
FROM CTE
WHERE CTE.[Quantity] - #RequiredQty > 0
)
INSERT INTO #T(BookingId,DiscountId,Quantity)
SELECT #BookingId,Rk,[Count] FROM CTE
option (maxrecursion 0)
select * from #T
SQLDEMO
This is another approach, but don't know if this code has better performance than cursor.
DECLARE #DiscountStocks TABLE (Id INT IDENTITY(1,1), DiscountId INT, LastQty INT)
INSERT INTO #DiscountStocks (DiscountId, LastQty) VALUES (1, 5)
INSERT INTO #DiscountStocks (DiscountId, LastQty) VALUES (2, 2)
INSERT INTO #DiscountStocks (DiscountId, LastQty) VALUES (3, 1)
DECLARE #DiscountBookings TABLE (Id INT IDENTITY(1,1), DiscountId INT, BookingId INT, Qty INT)
DECLARE #BookingDiscount TABLE (Id INT IDENTITY(1,1), BookingId INT, DiscountId INT, Qty INT)
INSERT INTO #BookingDiscount (BookingId, DiscountId, Qty) VALUES (1, 1, 4)
INSERT INTO #BookingDiscount (BookingId, DiscountId, Qty) VALUES (1, 2, 2)
INSERT INTO #BookingDiscount (BookingId, DiscountId, Qty) VALUES (1, 3, 1)
INSERT INTO #BookingDiscount (BookingId, DiscountId, Qty) VALUES (2, 1, 1)
INSERT INTO #BookingDiscount (BookingId, DiscountId, Qty) VALUES (2, 2, 2)
SELECT BD.Id AS BDId, DS.Id AS DSId, DS.LastQty, BD.Qty
, DS.LastQty - (SELECT SUM(Qty) FROM #BookingDiscount WHERE Id <= BD.Id AND DiscountId = BD.DiscountId) AS QtyAfterSubstract
INTO #LastDiscountStock
FROM #DiscountStocks DS
INNER JOIN #BookingDiscount BD ON DS.DiscountId = BD.DiscountId
ORDER BY BD.Id, DS.Id
INSERT INTO #DiscountBookings (DiscountId, BookingId, Qty)
SELECT DSId, BDId, Qty
FROM #LastDiscountStock
WHERE QtyAfterSubstract >= 0
DROP TABLE #LastDiscountStock
SELECT * FROM #DiscountBookings
I have a stored procedure that I inherited. The goal is for the data in the temp table: #multi_nominees_uf to be joined with the data in #temp_reviewers_UF and assign #temp_reviewers_UF.uf_rev_id to #multi_nominees_uf.application_number where the corresponding uf_rev_id's short_plan does not match the major associated with the appNumber's major .
It is not as simple as doing a JOIN.
The following has to be in place:
short_plan can not match the major(associated with the uf_rev_id)
count of each uf_rev_id can only be in the table a certain number of times (#RevsPerRevieweruf). Also, the uf_rev_id will be in the #temp_reviewers_uf table more than once with a different short_plan, it should only be looking at DISTINCT uf_rev_id when calculating the #RevPerRevieweruf.
The way it is written now, the counts are not consistent. One uf_rev_ID may have 122 records and another may have 50 - each distinct uf_rev_id should have the same count (or very close). I have researched and tried NTILE but I couldn't figure it out.
Any ideas of the best way to accomplish this?? Any input is appreciated.
-----Sample Data -----
CREATE TABLE #mult_nominees_uf(
appnum VARCHAR(8)
,major VARCHAR(8)
,compid INT
);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('00012345','ACT',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('10002343','BBC',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('10002777','BBC',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('10000023','DED',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('23457829','AAR',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('78954321','RRE',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('90002342','ACT',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('11156726','AAR',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('88855593','RRE',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('10000001','DED',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('20000393','ACT',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('11119999','DED',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('78927626','AAR',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('67589393','RRE',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('12453647','AAR',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('00012345','ACT',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('10002343','BBC',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('10002777','BBC',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('10000023','DED`',2);
INSERT INTO #mult_nominees_uf(appnum,major,compid) VALUES ('23457829','AAR',2);
--with this sample data the #RevsPerReviewerUF count would be 4 since A5 is listed twice and we only want distinct values used
CREATE TABLE #Temp_Reviewers_uf(
uf_rev_id VARCHAR(8)
,short_plan VARCHAR(8)
,fac_emplid INTEGER
);
INSERT INTO #Temp_Reviewers_uf(uf_rev_id,short_plan,fac_emplid) VALUES ('A1','ACT',00000012);
INSERT INTO #Temp_Reviewers_uf(uf_rev_id,short_plan,fac_emplid) VALUES ('A2','BBC',00000145);
INSERT INTO #Temp_Reviewers_uf(uf_rev_id,short_plan,fac_emplid) VALUES ('A3','DED',10002934);
INSERT INTO #Temp_Reviewers_uf(uf_rev_id,short_plan,fac_emplid) VALUES ('A5','RRE',90001223);
INSERT INTO #Temp_Reviewers_uf(uf_rev_id,short_plan,fac_emplid) VALUES ('A5','ACT',90001223);
----Stored procedure -
DECLARE #Index INT
DECLARE #Num_nomineesUF INT
DECLARE #Num_reviewersUF INT
DECLARE #Num_reviewersUFDISTINCT INT
DECLARE #Num_reviews INT
DECLARE #Rev_ID nvarchar(25), #Nom_ID varchar(8), #Short_Plan varchar(8), #Major varchar(8)
DECLARE #RevsPerReviewerUF INT
SET #Num_reviews = 4
DECLARE #actualCompID int
DECLARE #UF_Flag INT
DECLARE #InsertNum int
SET #InsertNum = 1
create table #mult_nominees_UF (appNumber varchar(8), Major varchar(8), comp_id INT)
create table #TempNomineeTable (uf_rev_id varchar(8), fac_emplid varchar(9), appNumber varchar(8), Major varchar(8), short_plan varchar(8), comp_id int)
create table #Temp_Reviewers_UF (uf_rev_id varchar(8), short_plan varchar(8), fac_emplid varchar(9)) -- temp table used to hold Nom_IDs already assigned to Rev_IDs
set #actualCompID = 21
-- * * SELECT APPLICATION NUMBER & MAJOR FROM FS_RESULTS TABLE * * * * * --
select appNumber, LEFT(Major, CHARINDEX('-', Major)-1) as Major, comp_id into #Delete_nomineesUF
from FS_Results
where UF='Y'
and comp_id = #actualCompID
and nominated=1;
SET #Num_nomineesUF = ##rowcount; --GET RECORD COUNT
IF (#Num_nomineesUF > 0)
BEGIN
SET #UF_Flag = 1;
END
SET #Index = 1 ; -- reinit variable
WHILE #Index <= 4 BEGIN
if (#UF_Flag > 0)
BEGIN
INSERT into #mult_nominees_uf
select * from #Delete_nomineesUF
END
-- Create temp table for UF Reviewers
select uf_rev_id, short_plan, fac_emplid into #temp_reviewers_UF
from ReviewersID_ShortPlan
where uf_rev_id like 'UF%'
and competition_id = #actualCompID
SET #Num_reviewersUF = ##rowcount
SELECT DISTINCT UF_REV_ID FROM ReviewersID_ShortPlan WHERE UF_REV_ID like 'UF%' AND competition_id = #actualCompID
SET #Num_reviewersUFDistinct = ##rowcount
SET #RevsPerReviewerUF = (#Num_nomineesUF * #Num_reviews) / nullif(#Num_reviewersUFDistinct,0)
WITH Match_NomineesWithReviewers AS(
SELECT DISTINCT
appNumber,
RTRIM(Major) AS Major,
COUNT(1) as rowcnt,
comp_id
FROM #mult_nominees_uf
GROUP BY appNumber,
RTRIM(Major),
comp_id
)
, rownum_matches AS (
SELECT m.appNumber,
m.Major,
t.short_plan,
t.uf_rev_id,
t.fac_emplid,
m.rowcnt,
m.comp_id,
ROW_NUMBER() OVER (PARTITION BY m.appNumber order by newid()) AS rownum
FROM Match_NomineesWithReviewers m
JOIN #temp_reviewers_UF t ON t.short_plan != m.major
GROUP BY m.appNumber, m.Major, t.short_plan,
t.uf_rev_id, t.fac_emplid, m.rowcnt, m.comp_id
HAVING COUNT(t.uf_rev_id) <= #RevsPerRevieweruf
)
INSERT INTO #TempNomineeTable
SELECT uf_rev_id, fac_emplid, appNumber, Major, short_plan, null, 0, null, comp_id FROM rownum_matches rm
WHERE rownum <= rowcnt
group by uf_rev_id, fac_emplid, appNumber, Major, short_plan, comp_id
HAVING COUNT(uf_rev_id) <= #RevsPerRevieweruf
I have a stored procedure that is meant to update two tables at once.
My problem here is that the first table has an auto-incrementing ID column ("commentID") and my second table has a relationship on this so I need the newly created ID from the first INSERT in order to make the second INSERT.
I tried the following which I can save without errors but it doesnt execute as it should and does not update the tables as intended.
Can someone tell me what I am doing wrong here ?
My SQL:
ALTER PROCEDURE [dbo].[MOC_UpdateComment]
#imgID int,
#commentID int = '999999',
#comment nvarchar(1000),
#lastUpdate nvarchar(50),
#modBy varchar(50)
AS
BEGIN
DECLARE #temp AS TABLE
(
commentID int
)
SET NOCOUNT ON;
BEGIN TRANSACTION;
INSERT INTO MOC_BlogComments
(
imgID,
comment
)
OUTPUT inserted.commentID INTO #temp(commentID)
SELECT #imgID,
#comment
INSERT INTO MOC_LogComments
(
commentID,
lastUpdate,
modTime,
modBy
)
SELECT commentID,
#lastUpdate,
GETDATE(),
#modBy
FROM #temp
COMMIT TRANSACTION;
END
DECLARE #imgID INT,
#commentID INT = '999999',
#comment NVARCHAR(1000),
#lastUpdate NVARCHAR(50),
#modBy VARCHAR(50)
DECLARE #MORC_BlogComments AS TABLE
(
id INT IDENTITY(1, 1) NOT NULL,
imgid INT,
comment VARCHAR(100)
)
DECLARE #MORC_LogComments AS TABLE
(
commentid INT,
lastupdate DATETIME,
modtime DATETIME,
modby VARCHAR(100)
)
DECLARE #TEMP AS TABLE
(
commentid INT
)
SET nocount ON;
BEGIN TRANSACTION;
INSERT INTO #MORC_BlogComments
(imgid,
comment)
output inserted.id
INTO #TEMP(commentid)
VALUES (#imgID,
#comment)
INSERT INTO #MORC_LogComments
(commentid,
lastupdate,
modtime,
modby)
SELECT commentid,
#lastUpdate,
Getdate(),
#modBy
FROM #temp
SELECT *
FROM #MORC_LogComments
Function SCOPE_IDENTITY() returns the identity of last insert operation. You can use it to get the value which you need to use in second INSERT statement
You can use it like this in your statement:
INSERT INTO MORC_BlogComments (imgID, comment)
VALUES (#imgID, #comment)
INSERT INTO MORC_LogComments (commentID, lastUpdate, modTime, modBy)
VALUES (SCOPE_IDENTITY(), #lastUpdate, GETDATE(), #modBy)
So I am using a cursor to loop through a bunch of records that my query returns. I have just updated some details in a table and now I want to pull the details from that table so I have used a temporary table.
So now I want to insert some values into a new table that are unrelated to the last and then the rest of the values would be a direct copy from the table variable...how can I do this?
I'll post below the section in question to help people see what I am trying to do.
The part in question is between the update status comment and the above not finished comment.
OPEN cur
FETCH NEXT FROM cur INTO #MembershipTermID , #EndDate , #MembershipID <VARIABLES>
WHILE ##FETCH_STATUS = 0
BEGIN
--PERFORM ACTION
DECLARE #TodaysDate DATETIME
SET #TodaysDate = getDate()
--CANCEL DETAIL
DECLARE #CancellationDetailID INT
INSERT INTO CancellationDetail(CancellationDetailID,RefundAmount,OldEndDate,EffectiveDate,CancelDate,ReasonCodeProgKey)
VALUES (0, 0.0, #EndDate, #TodaysDate, #TodaysDate, 'CANC_DORMANT')
SELECT #CancellationDetailID = SCOPE_IDENTITY()
INSERT INTO CancellationDetailAudit(StampUser,StampDateTime,StampAction,CancellationDetailID,RefundAmount,OldEndDate,EffectiveDate,CancelDate,ReasonCodeProgKey)
VALUES('SYSTEM', GetDate(), 'I', #CancellationDetailID, 0.0, #EndDate, #TodaysDate, #TodaysDate, 'CANC_DORMANT')
--LINK TO TERM
INSERT INTO MembershipTermCancellationDetail(CancellationDetailID,MembershipTermID)
VALUES(#CancellationDetailID, #MembershipTermID)
INSERT INTO MembershipTermCancellationDetailAudit(StampUser,StampDateTime,StampAction,MembershipTermCancellationDetailID,CancellationDetailID,MembershipTermID)
VALUES('SYSTEM', GetDate(), 'I', 0, #CancellationDetailID, #MembershipTermID)
--UPDATE STATUS
UPDATE MembershipTerm
SET MemberStatusProgKey = 'CANCELLED',
EndDate = #TodaysDate,
UpdateDateTime = #TodaysDate,
AgentID = 224,
NextTermPrePaid = 'False'
WHERE MembershipTermID = #MembershipTermID
DECLARE #MembershipTermTable TABLE
(
MembershipTermID int,
MemberStatusProgKey nvarchar (50),
StartDate datetime,
EndDate datetime,
AdditionalDiscount float,
EntryDateTime datetime,
UpdateDateTime datetime,
MembershipID int,
AgentID smallint,
PlanVersionID int,
ForceThroughReference nvarchar (255),
IsForceThrough bit,
NextTermPrePaid bit,
IsBillingMonthly bit,
LastPaymentDate datetime,
PaidToDate datetime,
IsIndeterminate bit
)
INSERT INTO #MembershipTermTable
SELECT MembershipTermID,
MemberStatusProgKey,
StartDate,
EndDate,
AdditionalDiscount,
EntryDateTime,
UpdateDateTime,
MembershipID,
AgentID,
PlanVersionID,
ForceThroughReference,
IsForceThrough,
NextTermPrePaid,
IsBillingMonthly,
LastPaymentDate,
PaidToDate,
IsIndeterminate
FROM MembershipTerm
WHERE MembershipTermID = #MembershipTermID
INSERT INTO MembershipTermAudit(StampUser,StampDateTime,StampAction,MembershipTermID,MemberStatusProgKey,StartDate,EndDate,AdditionalDiscount,EntryDateTime,UpdateDateTime,MembershipID,AgentID,PlanVersionID,ForceThroughReference,IsForceThrough,NextTermPrePaid,IsBillingMonthly,LastPaymentDate,PaidToDate,IsIndeterminate)
VALUES ('SYSTEM',#TodaysDate,'I',MembershipTermID,MemberStatusProgKey,StartDate,EndDate,AdditionalDiscount,EntryDateTime,UpdateDateTime,MembershipID,AgentID,PlanVersionID,ForceThroughReference,IsForceThrough,NextTermPrePaid,IsBillingMonthly,LastPaymentDate,PaidToDate,IsIndeterminate)
--ABOVE NOT FINISHED, NEED TO ADD AUDIT RECORD CORRECTLY
--Members
DECLARE #MembersTable TABLE
(
MembershipTermID int,
MemberStatusProgKey nvarchar (50),
StartDate datetime,
EndDate datetime,
AdditionalDiscount float,
EntryDateTime datetime,
UpdateDateTime datetime,
MembershipID int,
AgentID smallint,
PlanVersionID int,
ForceThroughReference nvarchar (255),
IsForceThrough bit,
NextTermPrePaid bit,
IsBillingMonthly bit,
LastPaymentDate datetime,
PaidToDate datetime,
IsIndeterminate bit
)
INSERT INTO #MembersTable
SELECT * FROM [MembershipTermPerson] WHERE MembershipTermID = #MembershipTermID
--Vehicles
FETCH NEXT FROM cur INTO #MembershipTermID , #EndDate , #MembershipID <VARIABLES>
END
CLOSE cur
DEALLOCATE cur
I think this would be a good case for a INSERT INTO SELECT statement
Something like
INSERT INTO MyTable (ColA, ColB, ColC)
SELECT
GETDATE(), A.MyCol, 'MyValue'
FROM MyOtherTable A
WHERE a.MyValue = 'What I Want'
Basically you skip the temp table, and just grab the value and inject everything at once.