Update table with stored procedure without null - sql-server

I tried to implement procedure which main goal is to store data into new separate table.First I create table which I want to populate with data
CREATE TABLE dbo.CustomerReportLogs (
ID int IDENTITY (1,1) NOT NULL,
CustomerFullName NVARCHAR(100) NULL,
LocationName NVARCHAR(100) NULL,
Amount decimal (18,2) NULL,
Currency NVARCHAR (20) NULL,
EmployeeId int NULL,
ValidFrom date NULL,
ValidTo date NULL,
CONSTRAINT PK_ID_CustomerReportLogs PRIMARY KEY CLUSTERED (
ID ASC
))
GO
So next step is how to populate this table with stored procedure. I order to do this I wrote this lines of code:
CREATE OR ALTER PROCEDURE dbo.procedure2 (#CustomerId int, #validFrom date, #ValidTo date,#EmployeeID int)
AS
BEGIN
SELECT CONCAT(c.FirstName, ' ', c.LastName) AS CustomerFullName, lo.Name as LocationName,acd.Amount as Amount,cu.Name as Currency,acc.EmployeeId,#validFrom as ValidFrom,#ValidTo as ValidTo
FROM dbo.Customer as c
INNER JOIN dbo.Account AS acc ON acc.CurrencyId=c.Id
INNER JOIN dbo.AccountDetails AS acd ON acd.AccountId=acc.Id
INNER JOIN dbo.Currency AS cu ON cu.id=acc.CurrencyId
INNER JOIN dbo.Location as lo ON lo.Id=acd.LocationId
INNER JOIN dbo.Employee AS emp ON emp.ID=acc.EmployeeId
WHERE acc.CustomerId=#CustomerId and acd.TransactionDate between #validFrom and #ValidTo and acc.EmployeeId=#EmployeeID
DECLARE #CustomerFullName NVARCHAR(100)
DECLARE #LocationName NVARCHAR(100)
DECLARE #Amount decimal (18,2)
DECLARE #Currency NVARCHAR (20)
INSERT INTO dbo.CustomerReportLogs(CustomerFullName,LocationName,Amount,Currency,EmployeeId,ValidFrom,ValidTo)
VALUES (#CustomerFullName,#LocationName,#Amount,#Currency,#EmployeeId,#ValidFrom,#ValidTo)
SELECT #CustomerFullName as CustomerFullName,#LocationName AS LocationName,#Amount AS Amount,#Currency as Currency,
#EmployeeId as EmployeeId,#ValidFrom as ValidFrom ,#ValidTo as ValidTo
END
GO
Above line code create stored procudure but now new problem arise namely when I try to execute first whit this command
EXEC dbo.procedure2 #CustomerId=8,#validFrom='2019.01.25', #ValidTo='2019.03.01', #EmployeeID=8
So this procedure can't update properly dbo.CustomerReportLogs so I got some results with null and some with values.Output you can see on pic below:
[![enter image description here][1]][1]
So can anybody help me how to update this table properly not with null

CREATE OR ALTER PROCEDURE dbo.procedure2 (
#CustomerId INT
,#validFrom DATE
,#ValidTo DATE
,#EmployeeID INT
)
AS
BEGIN
INSERT INTO dbo.CustomerReportLogs (
CustomerFullName
,LocationName
,Amount
,Currency
,EmployeeId
,ValidFrom
,ValidTo
)
OUTPUT INSERTED.[CustomerFullName],INSERTED.[LocationName],INSERTED.[Amount],INSERTED.[Currency],INSERTED.[EmployeeId],INSERTED.[ValidFrom] ,INSERTED.[ValidTo]
SELECT CONCAT (c.FirstName,' ',c.LastName) AS CustomerFullName
,lo.Name AS LocationName
,acd.Amount AS Amount
,cu.Name AS Currency
,acc.EmployeeId
,#validFrom AS ValidFrom
,#ValidTo AS ValidTo
FROM dbo.Customer AS c
INNER JOIN dbo.Account AS acc ON acc.CurrencyId = c.Id
INNER JOIN dbo.AccountDetails AS acd ON acd.AccountId = acc.Id
INNER JOIN dbo.Currency AS cu ON cu.id = acc.CurrencyId
INNER JOIN dbo.Location AS lo ON lo.Id = acd.LocationId
INNER JOIN dbo.Employee AS emp ON emp.ID = acc.EmployeeId
WHERE acc.CustomerId = #CustomerId
AND acd.TransactionDate BETWEEN #validFrom
AND #ValidTo
AND acc.EmployeeId = #EmployeeID
END

Related

Insert values into table with procedure

I tried to implement procedure which main goal is to store data into separate table.I order to do this first I started with simple query with scalar variables. Below you can see code:
DECLARE #CustomerId int=8
DECLARE #validFrom date='2019.01.01'
DECLARE #ValidTo date='2019.03.01'
DECLARE #EmployeeID int=8
SELECT CONCAT(c.FirstName, ' ', c.LastName) AS CustomerFullName, lo.Name as LocationName,acd.Amount,cu.Name as Currency,acc.EmployeeId,#validFrom as ValidFrom,#ValidTo as ValidTo,CONCAT(emp.FirstName, ' ', emp.LastName) AS EmployeeFullName
FROM dbo.Customer as c
INNER JOIN dbo.Account AS acc ON acc.CurrencyId=c.Id
INNER JOIN dbo.AccountDetails AS acd ON acd.AccountId=acc.Id
INNER JOIN dbo.Currency AS cu ON cu.id=acc.CurrencyId
INNER JOIN dbo.Location as lo ON lo.Id=acd.LocationId
INNER JOIN dbo.Employee AS emp ON emp.ID=acc.EmployeeId
WHERE acc.CustomerId=#CustomerId and acd.TransactionDate between #validFrom and #ValidTo and acc.EmployeeId=#EmployeeID
So code above works great and give me expect results.
So next step is to put this code into procedure in order to filling table with data from procedure.For that reason I make table and also I try to put code above into procedure
CREATE TABLE dbo.CustomerReportLogs (
ID int IDENTITY (1,1) NOT NULL,
CustomerFullName NVARCHAR(100) NOT NULL,
LocationName NVARCHAR(100) NOT NULL,
Amount decimal (18,2) NOT NULL,
Currency NVARCHAR (20)NOT NULL,
EmployeeId int NOT NULL,
ValidFrom date NOT NULL,
ValidTo date NOT NULL,
EmployeeFullName NVARCHAR(100) NOT NULL,
CONSTRAINT PK_ID_CustomerReportLogs PRIMARY KEY CLUSTERED (
ID ASC
))
GO
CREATE OR ALTER PROCEDURE dbo.procedure1 (#CustomerId int, #validFrom date, #ValidTo date,#EmployeeID int)
AS
BEGIN
SELECT CONCAT(c.FirstName, ' ', c.LastName) AS CustomerFullName, lo.Name as LocationName,acd.Amount,cu.Name as Currency,acc.EmployeeId,#validFrom as ValidFrom,#ValidTo as ValidTo,CONCAT(emp.FirstName, ' ', emp.LastName) AS EmployeeFullName
FROM dbo.Customer as c
INNER JOIN dbo.Account AS acc ON acc.CurrencyId=c.Id
INNER JOIN dbo.AccountDetails AS acd ON acd.AccountId=acc.Id
INNER JOIN dbo.Currency AS cu ON cu.id=acc.CurrencyId
INNER JOIN dbo.Location as lo ON lo.Id=acd.LocationId
INNER JOIN dbo.Employee AS emp ON emp.ID=acc.EmployeeId
WHERE acc.CustomerId=#CustomerId and acd.TransactionDate between #validFrom and #ValidTo and acc.EmployeeId=#EmployeeID
SELECT *
INSERT INTO dbo.CustomerReportLogs(CustomerFullName,LocationName,Amount,Currency,EmployeeId,ValidFrom,ValidTo,EmployeeFullName)
VALUES (#CustomerFullName,#LocationName,#Amount,#Currency,#EmployeeId,#ValidFrom,#ValidTo,#EmployeeFullName)
Return
END
GO
Error message from above procedure is that I need to declare scalar variable #CustomerFullName,but this variable actually I got from code with concat function and is not scalar. So probably in last part of my code I have some errors. So can anybody help me how to fix this errors?
Msg 137, Level 15, State 2, Procedure procedure1, Line 29 [Batch Start Line 3767]
Must declare the scalar variable "#CustomerFullName".
You aren't actually storing your returned values in variables. You could do that I.e. you first declare the variables and then use something like SELECT #CustomerFullName = CONCAT(c.FirstName, ' ', c.LastName) .... FROM ... , but far easier would be to replace your SELECT directly with the INSERT. I.e.
CREATE OR ALTER PROCEDURE dbo.procedure1 (#CustomerId int, #validFrom date, #ValidTo date,#EmployeeID int)
AS
BEGIN
INSERT INTO dbo.CustomerReportLogs(
CustomerFullName
, LocationName
, Amount
, Currency
, EmployeeId
, ValidFrom
, ValidTo
, EmployeeFullName
)
SELECT
CONCAT(c.FirstName, ' ', c.LastName) AS CustomerFullName
, lo.Name as LocationName
, acd.Amount
, cu.Name as Currency
, acc.EmployeeId
, #validFrom as ValidFrom
, #ValidTo as ValidTo
, CONCAT(emp.FirstName, ' ', emp.LastName) AS EmployeeFullName
FROM
dbo.Customer as c
INNER JOIN dbo.Account AS acc ON acc.CurrencyId=c.Id
INNER JOIN dbo.AccountDetails AS acd ON acd.AccountId=acc.Id
INNER JOIN dbo.Currency AS cu ON cu.id=acc.CurrencyId
INNER JOIN dbo.Location as lo ON lo.Id=acd.LocationId
INNER JOIN dbo.Employee AS emp ON emp.ID=acc.EmployeeId
WHERE
acc.CustomerId = #CustomerId
AND acd.TransactionDate BETWEEN #validFrom AND #ValidTo
AND acc.EmployeeId = #EmployeeID
END
Please note this has not been tested, but I just copy/pasted your own code

loop through rows and INSERT INTO SELECT from the same table

I'm trying to create a stored procedure in SQL-Server2012, that will update some rows, then re-insert them again into the same table but with NULLs or different calculated values.
my table 'schedule':
CREATE TABLE [cil].[schedule](
[id] [int] IDENTITY(1,1) NOT NULL,
[taskFK] [int] NULL,
[scheduledDate] [smalldatetime] NULL,
[completionDate] [smalldatetime] NULL,
[rotaCycle] [smallint] NULL,
[result] [smallint] NULL,
CONSTRAINT [PK_schedule] PRIMARY KEY CLUSTERED
my table 'task':
CREATE TABLE [cil].[task](
[id] [int] IDENTITY(1,1) NOT NULL,
[standard] [varchar](250) NULL,
[equipFK] [int] NULL,
[areaFK] [smallint] NULL,
CONSTRAINT [PK_task] PRIMARY KEY CLUSTERED
existing stored procedure:
CREATE PROCEDURE [cil].[updateCompletionDate]
#equipID int,
#myCompletionDate datetime
AS
UPDATE cil.schedule SET completionDate=#myCompletionDate
WHERE schedule.id IN (
SELECT schedule.id
FROM cil.schedule
LEFT JOIN cil.task
ON cil.schedule.taskFK=cil.task.id
WHERE CAST(scheduledDate AS DATE)<=CAST(GetDate() AS DATE)
AND completionDate IS NULL
AND result IS NOT NULL
AND equipFK=#equipID);
GO
and now I want to add the RE-INSERT to the above SP:
INSERT INTO cil.schedule (taskFK, scheduledDate, rotaCycle)
SELECT taskFK, scheduledDate = DATEADD(dd, (SELECT rotaCycle FROM
cil.schedule WHERE id=??),scheduledDate), rotaCycle
FROM cil.schedule LEFT JOIN cil.task ON task.id=schedule.taskFK
WHERE completionDate=#myCompletionDate
AND task.equipFK=#equipID;
Dont know how to loop through all ID from 1st part of the SP?
you can do this by using output clause and delete table. i have created below pseudo code to give you some idea how this will work -
CREATE PROCEDURE [cil].[updateCompletionDate]
#equipID int,
#myCompletionDate datetime
AS
DECLARE #MyTable table(
id int ,
taskFK int
.... ); -- declare all required columns
UPDATE cil.schedule SET completionDate=#myCompletionDate
OUTPUT deleted.id,
deleted.taskFK -- list of required columns you want
INTO #MyTable
WHERE schedule.id IN (
SELECT schedule.id
FROM cil.schedule
LEFT JOIN cil.task
ON cil.schedule.taskFK=cil.task.id
WHERE CAST(scheduledDate AS DATE)<=CAST(GetDate() AS DATE)
AND completionDate IS NULL
AND result IS NOT NULL
AND equipFK=#equipID)
INSERT INTO cil.schedule (taskFK, scheduledDate, rotaCycle)
select [required coluns]
from #MyTableVa join cil.schedule -- all requied join conditions
You can use SQL Output clause to update your table and insert effected rows into the same table
Please check following simple sample script
/*
create table OutputClauseSample (
Id int identity(1,1),
Code varchar(10),
Val int
)
insert into OutputClauseSample select 'A',10
insert into OutputClauseSample select 'B',20
insert into OutputClauseSample select 'C',30
*/
update OutputClauseSample
set Val = 2 * Val
output (deleted.Code)
into OutputClauseSample (Code)
where id = 3
select * from OutputClauseSample
here is my procedure, cursor loops through and re-inserts modified correctly data:
CREATE PROCEDURE [cil].[addComplDateAnd_ReSchedule]
#equipID int,
#myCompletionDate datetime2(6)
AS
/* add completion date */
UPDATE cil.schedule SET completionDate=#myCompletionDate
WHERE schedule.id IN (
SELECT schedule.id
FROM cil.schedule
LEFT JOIN cil.task ON cil.schedule.taskFK=cil.task.id
WHERE CAST(scheduledDate AS DATE)<=CAST(GetDate() AS DATE)
AND completionDate IS NULL
AND result IS NOT NULL
AND equipFK=#equipID);
/* reschedule tasks */
DECLARE #nextTaskID AS INT;
DECLARE #nextScheduledDate AS DATETIME2(6);
DECLARE #nextRotaCycle AS INT;
DECLARE db_cursor CURSOR FOR
SELECT taskFK, scheduledDate, rotaCycle
FROM cil.schedule
LEFT JOIN cil.task ON cil.schedule.taskFK=cil.task.id
WHERE completionDate=#myCompletionDate
AND equipFK=#equipID;
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO #nextTaskID, #nextScheduledDate, #nextRotaCycle;
WHILE ##FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
INSERT INTO cil.schedule (taskFK, scheduledDate, rotaCycle)
VALUES(#nextTaskID
,DATEADD(dd, #nextRotaCycle, #nextScheduledDate)
,#nextRotaCycle)
FETCH NEXT FROM db_cursor INTO #nextTaskID, #nextScheduledDate,
#nextRotaCycle;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
GO

but give me error that invalid object name #temp2

Alter procedure spMRI_TAG_try
#DocNum int
as
declare #cnt int
declare #count int
declare #cardname nvarchar(100)
declare #Docdate datetime
declare #itemCode nvarchar(50)
declare #Dscription nvarchar(100)
declare #Quantity numeric(19,6)
declare #ManBtchNum char(1)
declare #SalPackUn numeric(19,6)
declare #ExpDate datetime
begin
set #cnt = 1
select #Count = pdn1.Quantity/OITM.SalPackUn from pdn1 inner join OITM on pdn1.ItemCode=OITM.ItemCode
while #cnt <= #count
insert into #temp2 values(#cardname,#DocDate,#itemcode,#Dscription,#Quantity,#ManBtchNum,#SalPackUn,#ExpDate)
select #cardname = a.CardName,#DocDate=a.DocDate,#itemcode=b.ItemCode,#Dscription=b.Dscription,#Quantity=b.Quantity,#ManBtchNum=c.ManBtchNum,#SalPackUn=c.SalPackUn,#ExpDate=d.ExpDate
from OPDN a inner join PDN1 b on a.DocEntry = b.DocEntry inner join OITM c on c.ItemCode = b.ItemCode inner join OBTN d on c.ItemCode = d.ItemCode and a.DocNum=#DocNum and d.ExpDate is not null
set #cnt=#cnt+1
end
select * from #temp2
but gives me an invalid object name #temp2 error.
Create temp table before your while loop:
create table #temp2 (Cardname ...)
while #cnt <= #count
insert into #temp2 values(#cardname,#DocDate,#itemcode,#Dscription,#Quantity,#ManBtchNum,#SalPackUn,#ExpDate)
select #cardname = a.CardName,#DocDate=a.DocDate,#itemcode=b.ItemCode,#Dscription=b.Dscription,#Quantity=b.Quantity,#ManBtchNum=c.ManBtchNum,#SalPackUn=c.SalPackUn,#ExpDate=d.ExpDate
Two points here:
Not sure why you are using looping - Try set based approaches. You can solve most of the problems in set based queries
You can create temp tables using select * into #temp2... Check for that syntax in msdn
To be honest your SP is a one big messed up code :)
I suggest you to rewrite it like this:
ALTER PROCEDURE spMRI_TAG_try
#DocNum int
AS
--Drop table if it exists
IF OBJECT_ID(N'#temp2') IS NOT NULL DROP TABLE #temp2
--create table
CREATE TABLE #temp2 (
cardname nvarchar(100),
Docdate datetime,
itemCode nvarchar(50),
Dscription nvarchar(100),
Quantity numeric(19,6),
ManBtchNum char(1),
SalPackUn numeric(19,6),
ExpDate datetime
)
--Make the insertion
INSERT INTO #temp2
SELECT a.CardName,
a.DocDate,
b.ItemCode,
b.Dscription,
b.Quantity,
c.ManBtchNum,
c.SalPackUn,
d.ExpDate
FROM OPDN a
INNER JOIN PDN1 b
ON a.DocEntry = b.DocEntry
INNER JOIN OITM c
ON c.ItemCode = b.ItemCode
INNER JOIN OBTN d
ON c.ItemCode = d.ItemCode and a.DocNum=#DocNum and d.ExpDate is not null
--output
SELECT *
FROM #temp2
No need a while loop (I can not even understand how you will switch through the rows, in your solution it will write the same row the '#count' times), you can write all data directly in temp table.
You get error because of there is no #temp2 table on the moment you are trying to insert, also there is no checking if the table already exists.
As was noted in answer by Kannan Kandasamy, the one more way is to use SELECT * INTO #temp2, it can be achieved this way:
ALTER PROCEDURE spMRI_TAG_try
#DocNum int
AS
IF OBJECT_ID(N'#temp2') IS NOT NULL DROP TABLE #temp2
SELECT a.CardName,
a.DocDate,
b.ItemCode,
b.Dscription,
b.Quantity,
c.ManBtchNum,
c.SalPackUn,
d.ExpDate
INTO #temp2
FROM OPDN a
INNER JOIN PDN1 b
ON a.DocEntry = b.DocEntry
INNER JOIN OITM c
ON c.ItemCode = b.ItemCode
INNER JOIN OBTN d
ON c.ItemCode = d.ItemCode and a.DocNum=#DocNum and d.ExpDate is not null
SELECT *
FROM #temp2

How Can I speed up Multiple Left Outer Join,

this is MS-SQL Query
I have use Lots of Left Inner Join.
NumberOfRow = about 300,000 Rows
Result time is about 4sec.
How can I speed up this query?.
PK is Id, Indexed RegionID
DECLARE #Location TABLE
(
Id int IDENTITY(1,1) PRIMARY KEY not null,
RegionID int ,
RegionType int ,
SubClass int ,
RegionName nvarchar(255) ,
RegionNameLong nvarchar(512) ,
ParentRegionID int
)
INSERT INTO #Location (RegionID, RegionType, SubClass, RegionName, RegionNameLong, ParentRegionID)
SELECT ORIGIN.RegionID AS RegionID
,ORIGIN.RegionType AS RegionType
,ORIGIN.SubClass AS SubClass
,REFER.RegionName AS RegionName
,REFER.RegionNameLong AS RegionNameLong
,ORIGIN.ParentRegionID AS ParentRegionID
FROM Location_en_US AS ORIGIN
INNER JOIN Location_ko_KR AS REFER ON ORIGIN.RegionID = REFER.RegionID
SELECT
TOP 10
EN_1.RegionID, EN_1.RegionName, EN_2.RegionID, EN_2.RegionName, EN_3.RegionID, EN_3.RegionName, EN_4.RegionID, EN_4.RegionName, EN_5.RegionID, EN_5.RegionName, EN_6.RegionID, EN_6.RegionName
FROM #Location AS EN_1
LEFT OUTER JOIN #Location AS EN_2 ON EN_1.ParentRegionID = EN_2.RegionID
LEFT OUTER JOIN #Location AS EN_3 ON EN_2.ParentRegionID = EN_3.RegionID
LEFT OUTER JOIN #Location AS EN_4 ON EN_3.ParentRegionID = EN_4.RegionID
LEFT OUTER JOIN #Location AS EN_5 ON EN_4.ParentRegionID = EN_5.RegionID
LEFT OUTER JOIN #Location AS EN_6 ON EN_5.ParentRegionID = EN_6.RegionID
INNER JOIN RegionType AS RT ON EN_1.RegionType = RT.TypeCode AND RT.LanguageCode = 'en_US'
INNER JOIN SubClass AS SC ON EN_1.SubClass = SC.TypeCode AND SC.LanguageCode = 'en_US'
WHERE EN_1.RegionNameLong LIKE '%SEUOL%'
this is use hierarchyid, but lowest then left outer join
CREATE TABLE dbo.Location_en_US(
Id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
Level hierarchyid NOT NULL,
RegionID int NOT NULL,
RegionType int NOT NULL,
RelativeSignificance nvarchar(3) NULL,
SubClass int NULL,
RegionName nvarchar(255) NOT NULL,
RegionNameLong nvarchar(512) NOT NULL,
ParentRegionID int NULL,
CreatedAt datetime2 NULL DEFAULT (getdate()),
)
SELECT RegionName AS RegionName1,
(SELECT RegionName FROM Location_en_US WHERE Level = Location.Level.GetAncestor(1)) AS Level2,
(SELECT RegionName FROM Location_en_US WHERE Level = Location.Level.GetAncestor(2)) AS Level3,
(SELECT RegionName FROM Location_en_US WHERE Level = Location.Level.GetAncestor(3)) AS Level4,
(SELECT RegionName FROM Location_en_US WHERE Level = Location.Level.GetAncestor(4)) AS Level5,
(SELECT RegionName FROM Location_en_US WHERE Level = Location.Level.GetAncestor(5)) AS Level6
FROM Location_en_US AS Location WHERE RegionNameLong LIKE '%SEOUL%'
Should use HierarhyId tecnique for operating tree-like structures.
Build index for ParentRegionID, RegionID columns.
Also, None of the listed join tables are picked to query result set.
Best wishes!
You're joining on ParentRegionID and RegionID. An index on either column might help. You probably have to switch from a table variable #Location to a temporary table #Location before you can add an index.
After adding the index, examine the "Query Plan" from the Query menu to see how this helps.
Add an index on regionId.
You can't explicitly add indexes to a table variable, so use this trick:
DECLARE #Location TABLE
(
Id int IDENTITY(1,1) PRIMARY KEY not null,
RegionID int ,
RegionType int ,
SubClass int ,
RegionName nvarchar(255) ,
RegionNameLong nvarchar(512) ,
ParentRegionID int,
UNIQUE (regionId, id)
)
Also, your left joins don't do anything except probably multiplying the same record. Are you sure your query is correct?

Sql Server error [SQLState 42000] (Error 325)

I have a script that utilizes the new Merge Output clause. I've run it in 3 different instances (all non-Production environments) and it works great. When I tried running it in our production environment, I get the error:
Executed as user: xxx\xxx. Incorrect syntax near 'Merge'. You
may need to set the compatibility level of the current database to a
higher value to enable this feature. See help for the SET
COMPATIBILITY_LEVEL option of ALTER DATABASE. [SQLSTATE 42000] (Error
325) Incorrect syntax near 'Merge'. You may need to set the
compatibility level of the current database to a higher value to
enable this feature. See help for the SET COMPATIBILITY_LEVEL option
of ALTER DATABASE. [SQLSTATE 42000] (Error 325). The step failed.
I've checked the versions of each instance and they are all 10.0.4000.0. All of the non-system databases are set to compatibility level 90 (2005), and system databases are set to 100 (2008). What else do I need to check to see where my production instance is different from the other non-Production instances?
Here's the query:
Declare #user varchar(20),
#message varchar(max)
Set #user = 'ISS20120917-144'
Create Table #data
(
CustomerEventID_Surrogate Int Identity (1,1) Not Null Primary Key,
CustomerNumber Int Not Null,
ConvictionEventID Int Not Null,
CustomerEventHierarchyID Int Not Null,
SanctionEventID Int Not Null,
ReferenceNumber varchar(40) Null,
ConvictionACDID Int Null,
State_Code varchar(2) Not Null,
County_ID Int Null,
CitationCDLHolderValueID Int Null,
Hazmat Bit Null,
CMV Bit Null,
PassengerEndorsement Bit Null,
OccurrenceDate DateTime Not Null,
ConvictionDate DateTime Not Null,
CourtOrder Bit Null
)
Create Table #surrogatemap
(
CustomerEventID_Surrogate Int Not Null,
NewCustomerEventID Int Not Null
)
Create Table #surrogateHIDmap
(
NewCustomerEventID Int Not Null,
NewHistoryEventDetailID Int Not Null
)
Begin Tran
Begin Try
Insert Into #data
Select ce.Cust_No,
ce.CustomerEventID,
ceh.CustomerEventHierarchyID,
ceSAN.CustomerEventID,
ce.ReferenceNumber,
hed.ACDID,
hed.State_Code,
hed.County_ID,
hed.CitationCDLHolderValueID,
hed.Hazmat,
hed.CMV,
hed.PassengerEndorsement,
hed.OccurrenceDate,
Case When cd.ConvictionDate IS NOT NULL Then cd.ConvictionDate
Else hed.OccurrenceDate
End As [ConvictionDate],
hed.CourtOrder
From IADS..CustomerEvent ce
Inner Join IADS..HistoryEventDetail hed On hed.CustomerEventID = ce.CustomerEventID
And hed.EndDate IS NULL
Inner Join IADS..CustomerEventCode cec On cec.CustomerEventCodeID = hed.CustomerEventCodeID
And cec.CustomerEventCodeID <> -51
Left Outer Join IADS..ConvictionDetail cd On cd.HistoryEventDetailID = hed.HistoryEventDetailID
Inner Join IADS..CustomerEventHierarchy ceh On ceh.CustomerEventID = ce.CustomerEventID
And ceh.EndDate IS NULL
Inner Join IADS..CustomerEvent ceSAN On ceSAN.CustomerEventID = ceh.RelatedCustomerEventID
And ceSAN.CustomerEventDispositionID IS NULL
Inner Join IADS..CustomerSanctionDetail csd On csd.CustomerEventID = ceSAN.CustomerEventID
And csd.SanctionDiscardedReasonID IS NULL
Inner Join IADS..SanctionReasonCode src On src.SanctionReasonCodeID = csd.SanctionReasonCodeID
And src.SanctionReasonCodeID = -320
Where ce.CustomerEventDispositionID IS NULL
Merge Into IADS..CustomerEvent
Using #data As src On 1 = 0
When Not Matched Then
Insert
(
CustomerEventCategoryID,
Cust_No,
ReferenceNumber,
CreatedBy,
CreatedDate,
UpdatedBy,
UpdatedDate
)
Values
(
-2,
src.CustomerNumber,
src.ReferenceNumber,
#user,
GetDate(),
#user,
GetDate()
)
Output
src.CustomerEventID_Surrogate,
inserted.CustomerEventID
Into #surrogatemap;
Select sm.NewCustomerEventID,
-8 As [HistoryEventTypeID],
-51 As [CustomerEventCodeID],
131 As [ACDID],
d.State_Code,
d.County_ID,
d.CitationCDLHolderValueID,
d.OccurrenceDate,
d.ConvictionDate,
d.Hazmat,
d.CMV,
d.CourtOrder,
GETDATE() As [EffectiveDate],
#user As [UpdatedBy],
GETDATE() As [UpdatedDate],
d.ConvictionACDID,
d.PassengerEndorsement
Into #hiddata
From #data d
Inner Join #surrogatemap sm On sm.CustomerEventID_Surrogate = d.CustomerEventID_Surrogate
Merge Into IADS..HistoryEventDetail
Using #hiddata As src On 1 = 0
When Not Matched Then
Insert
(
CustomerEventID,
HistoryEventTypeID,
CustomerEventCodeID,
ACDID,
State_Code,
County_ID,
CitationCDLHolderValueID,
OccurrenceDate,
Hazmat,
CMV,
CourtOrder,
EffectiveDate,
UpdatedBy,
UpdatedDate,
UnderlyingACDID,
PassengerEndorsement
)
Values
(
src.NewCustomerEventID,
src.HistoryEventTypeID,
src.CustomerEventCodeID,
src.ACDID,
src.State_Code,
src.County_ID,
src.CitationCDLHolderValueID,
src.OccurrenceDate,
src.Hazmat,
src.CMV,
src.CourtOrder,
src.EffectiveDate,
src.UpdatedBy,
src.UpdatedDate,
src.ConvictionACDID,
src.PassengerEndorsement
)
Output
src.NewCustomerEventID,
inserted.HistoryEventDetailID
Into #surrogateHIDmap;
Insert Into IADS..CustomerEventHierarchy
(
CustomerEventID,
RelatedCustomerEventID,
EffectiveDate,
UpdatedBy,
UpdatedDate
)
Select sm.NewCustomerEventID,
d.SanctionEventID,
GETDATE(),
#user,
GETDATE()
From #data d
Inner Join #surrogatemap sm On sm.CustomerEventID_Surrogate = d.CustomerEventID_Surrogate
Insert Into IADS..CourtFineDetail
(
HistoryEventDetailID,
ConvictionDate
)
Select s.NewHistoryEventDetailID,
d.ConvictionDate
From #hiddata d
Inner Join #surrogateHIDmap s On s.NewCustomerEventID = d.NewCustomerEventID
-- Remove the tie to the SUS077
Update IADS..CustomerEventHierarchy
Set EndDate = GETDATE(),
UpdatedBy = #user,
UpdatedDate = GETDATE()
Where CustomerEventHierarchyID In (Select CustomerEventHierarchyID From #data)
-- Build temp table containing the records that have already purged
Select ce.Cust_No,
ce.CustomerEventID,
ceh.CustomerEventHierarchyID
Into #disposedRecords
From IADS..CustomerEvent ce
Inner Join IADS..HistoryEventDetail hed On hed.CustomerEventID = ce.CustomerEventID
And hed.EndDate IS NULL
Inner Join IADS..CustomerEventCode cec On cec.CustomerEventCodeID = hed.CustomerEventCodeID
And hed.CustomerEventCodeID <> -51
Inner Join IADS..CustomerEventHierarchy ceh On ceh.CustomerEventID = ce.CustomerEventID
And ceh.EndDate IS NULL
Inner Join IADS..CustomerEvent ceSAN On ceSAN.CustomerEventID = ceh.RelatedCustomerEventID
And ceSAN.CustomerEventDispositionID IS NOT NULL
Inner Join IADS..CustomerSanctionDetail csd On csd.CustomerEventID = ceSAN.CustomerEventID
And csd.SanctionReasonCodeID = -320
Where ce.CustomerEventDispositionID IS NOT NULL
Order By ce.CustomerEventDispositionDate Desc
-- Un-purge all of the records that were previously tied to a SUS077
Update IADS..CustomerEvent
Set CustomerEventDispositionID = Null,
CustomerEventDispositionComment = Null,
CustomerEventDispositionDate = Null,
UpdatedBy = #user,
UpdatedDate = GETDATE()
Where CustomerEventID In (Select CustomerEventID From #disposedRecords)
-- Remove the records from the PURGEEventsReadyForPurge table
Delete
From IADS..PURGEEventsReadyForPurge
Where CustomerEventID In (Select CustomerEventID From #disposedRecords)
-- Remove tie of purged records
Update IADS..CustomerEventHierarchy
Set EndDate = GETDATE(),
UpdatedBy = #user,
UpdatedDate = GETDATE()
Where CustomerEventHierarchyID In (Select CustomerEventHierarchyID From #disposedRecords)
Delete From IADS..PURGEEventsReadyForPurge Where PURGEEventsReadyForPurgeID In
(
Select PURGEEventsReadyForPurgeID
From IADS..PURGEEventsReadyForPurge p
Inner Join IADS..CustomerEvent ce On ce.CustomerEventID = p.CustomerEventID
And ce.CustomerEventDispositionID IS NULL
Inner Join IADS..CustomerEventCategory ceg On ceg.CustomerEventCategoryID = ce.CustomerEventCategoryID
Left Outer Join IADS..CustomerEventHierarchy ceh On ceh.CustomerEventID = ce.CustomerEventID
Left Outer Join IADS..CustomerEventHierarchy ceh2 On ceh2.RelatedCustomerEventID = ce.CustomerEventID
Where p.PurgeDate IS NOT NULL
)
Drop Table #disposedRecords
Drop Table #hiddata
Drop Table #surrogateHIDmap
Drop Table #surrogatemap
Drop Table #data
Commit
End Try
Begin Catch
Drop Table #disposedRecords
Drop Table #hiddata
Drop Table #surrogateHIDmap
Drop Table #surrogatemap
Drop Table #data
Rollback
End Catch
You can try any of these two things..
1. Update the compatiability level to 100.
ALTER DATABASE [dbname] SET COMPATIBILITY_LEVEL = 100
2. End the MERGE statement and the statement previous to MERGE with a semicolon (;)
Hope it works.

Resources