Sql Server error [SQLState 42000] (Error 325) - sql-server

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.

Related

Update table with stored procedure without null

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

Create trigger with log information about table update

I need to create a trigger which inserts into another table information about price changes. Below I present my solution.
CREATE TABLE Production.Products_AUDIT
(
auditid INT NOT NULL IDENTITY,
productid INT NULL,
old_price MONEY NOT NULL,
new_price MONEY NOT NULL,
CONSTRAINT PK_Products_AUDIT PRIMARY KEY(auditid),
CONSTRAINT FK_Products_AUDIT_AUDIT
FOREIGN KEY(productid) REFERENCES Production.Products(productid)
);
INSERT INTO Production.Products_AUDIT VALUES (1, 18 , 20)
INSERT INTO Production.Products_AUDIT VALUES (2, 19 , 31)
DELETE FROM Production.Products_AUDIT
SELECT unitprice
FROM Production.Products_AUDIT as p1
INNER JOIN Production.Products as p2 on p1.productid = p2.productid
CREATE TRIGGER trig1
ON Production.Products
FOR UPDATE
AS
declare #prodId INT
declare #oldPrice MONEY
declare #newPrice MONEY
SET #prodId = (SELECT i.productid
FROM inserted as i
INNER JOIN Production.Products as pp on i.productid = pp.productid )
SET #oldPrice = (SELECT i.unitprice
FROM deleted as i
INNER JOIN Production.Products as pp on i.productid = pp.productid )
SET #newPrice = (SELECT i.unitprice
FROM inserted as i
INNER JOIN Production.Products as pp on i.productid = pp.productid)
INSERT INTO Production.Products_AUDIT
VALUES(#prodId, #oldPrice, #newPrice)
UPDATE Production.Products
SET unitprice = 45
WHERE productid < 2
SELECT * FROM Production.Products_AUDIT
Everything is OK when I update only one record. The problem is when I try to update many records, then I see the error below:
Msg 512, Level 16, State 1, Procedure trig1, Line 41
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The
statement has been terminated.
Does anyone know how to fix this problem?
The problem is that Triggers are fired on a statement bases, and not on a row bases. This means that your trigger is fired once for all the rows updated in your statement, so the inserted and deleted tables might contain more than one row.
However, your trigger code does not take that into consideration, thus raising an error.
Try this instead:
CREATE TRIGGER Products_ForUpdate
ON Production.Products
FOR UPDATE
AS
INSERT INTO Production.Products_AUDIT
SELECT i.productid, d.unitprice, i.unitprice
FROM inserted as i
INNER JOIN Production.Products as pp on i.productid = pp.productid
INNER JOIN deleted as d ON pp.productid = d.productid
The trigger is fired for each Update statement not for each row in an update statement. You do not need any of these variables at all, just select data (old and New) data from inserted and deleted tables and insert it into the audit table directly, something like this........
CREATE TRIGGER trig1
ON Production.Products
FOR UPDATE
as
BEGIN
SET NOCOUNT ON;
INSERT INTO Production.Products_AUDIT (productid , Old_Price , New_Price)
SELECT pp.productid
, d.unitprice AS OldPrice
, i.unitprice AS NewPrice
FROM Production.Products as pp
INNER JOIN inserted i ON i.productid = pp.productid
INNER JOIN deleted d ON d.productid = pp.productid
END

Executing stored procedure not working but individual statements working in stored procedure

I have the following stored procedure which I am trying to execute.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_Create]
(
#OriginatingTransactionID VARCHAR(50),
#AssociatedOriginatingTransactionID VARCHAR(50),
#LineOfBusiness VARCHAR(50),
#RiskState VARCHAR(50),
#OccupationCode VARCHAR(50),
#SourceSystem VARCHAR(50),
#DocumentCategory VARCHAR(50),
#DocumentType VARCHAR(50),
#TransactionFlow VARCHAR(50),
#BundleName VARCHAR(50),
#DocumentID VARCHAR(50),
#DocumentName VARCHAR(50),
#PolicyOrClaimNumber VARCHAR(50),
#EffectiveOrCreationDate DATETIME,
#SignatureDetect BIT
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #FinalDate DATETIME, #RuleID VARCHAR(50),
#RuleName VARCHAR(50), #CurrentActionID INT,
#BundleTransactionID INT
IF (#SignatureDetect = 'true')
BEGIN
IF (#OriginatingTransactionID = #AssociatedOriginatingTransactionID)
BEGIN
IF NOT EXISTS (SELECT t.Doc_Checklist_TXN_ID FROM (SELECT bundlechecklist.Bundle_TXN_ID, documentchecklist.Doc_Checklist_TXN_ID, documentchecklist.Doc_Type_Name FROM ecm.bundle_checklist_txn bundlechecklist
LEFT OUTER JOIN [ECM].[Document_Checklist_TXN] documentchecklist ON documentchecklist.Bundle_TXN_ID = bundlechecklist.Bundle_TXN_ID
WHERE bundlechecklist.originating_tran_id = #OriginatingTransactionID AND bundle_name = #BundleName)t WHERE t.Doc_Checklist_TXN_ID is not null )
BEGIN
UPDATE ecm.bundle_checklist_txn
SET Bundle_Status_Code = 'COMP'
FROM ecm.bundle_checklist_txn bundlechecklist
INNER JOIN (SELECT DISTINCT Bundle_TXN_ID,Document_ID FROM ecm.Document_Checklist_TXN documentchecklist
WHERE Doc_Status_Code='COMP') COMP
ON COMP.Bundle_TXN_ID = bundlechecklist.Bundle_TXN_ID
AND COMP.Bundle_TXN_ID NOT IN (
SELECT Bundle_TXN_ID FROM ecm.Document_Checklist_TXN documentchecklist
WHERE documentchecklist.Bundle_TXN_ID=COMP.Bundle_TXN_ID AND documentchecklist.Doc_Status_Code<>'COMP')
AND COMP.Document_ID=#DocumentID
WHERE bundlechecklist.Bundle_TXN_ID= #OriginatingTransactionID
AND bundlechecklist.Assoc_Orig_Tran_ID=#AssociatedOriginatingTransactionID
UPDATE associatedtransaction
SET Assoc_Orig_Status_Code='COMP'
FROM [ECM].[Assoc_Orig_Tran_TXN] associatedtransaction
INNER JOIN (SELECT DISTINCT Assoc_Orig_Tran_ID from [ECM].[Bundle_Checklist_TXN] bundlechecklist
WHERE bundlechecklist.[Bundle_Status_Code]='COMP')COMP
ON COMP.Assoc_Orig_Tran_ID=associatedtransaction.Assoc_Orig_Tran_ID
WHERE COMP.Assoc_Orig_Tran_ID=#AssociatedOriginatingTransactionID
END
END
END
ELSE
BEGIN
IF (#OriginatingTransactionID = #AssociatedOriginatingTransactionID)
BEGIN
SELECT #FinalDate =DATEADD(DAY,Number_Of_Days_Till_Next_Action,#EffectiveOrCreationDate),#RuleID= rule1.Action_Rule_ID,#RuleName=rule1.Action_Rule_Name,#currentActionID=rule1.Current_Action_ID FROM ecm.Action_Rule rule1
INNER JOIN ecm.Action_Rule_Group rulegroup ON rulegroup.Action_Rule_Group_ID = rule1.Action_Rule_Group_ID
INNER JOIN ref.Line_of_Business lob ON lob.Line_of_Business_Code = rulegroup.Line_of_Business_Code
INNER JOIN ref.State state ON state.State_Alpha_Code=rulegroup.State_Alpha_Code
INNER JOIN ref.Source_System sourcesystem ON sourcesystem.Source_System_ID = rulegroup.Source_System_ID
INNER JOIN ecm.[Document Catgeory] documentcategory ON documentcategory.Doc_Categ_ID = rulegroup.Doc_Categ_ID
INNER JOIN ecm.[Document Type] documenttype ON documenttype.Doc_Type_ID=rule1.Doc_Type_ID
INNER JOIN ecm.Exec_Acct_Group occupationgroup ON occupationgroup.Exec_Acct_Grp_ID = rulegroup.Exec_Acct_Grp_ID
INNER JOIN [ECM].[Bundle] bundle ON bundle.Bundle_ID = rule1.Bundle_ID
WHERE
bundle.Bundle_Name = #BundleName
AND rulegroup.Line_of_Business_Code=#LineOfBusiness
AND rulegroup.State_Alpha_Code=#RiskState
AND documentcategory.Doc_Categ_Name=#DocumentCategory
AND rulegroup.Exec_Acct_Grp_ID=#OccupationCode
AND rule1.Transaction_Flow=#TransactionFlow
AND sourcesystem.Source_System_Name = #SourceSystem
AND rulegroup.Doc_Categ_ID=documentcategory.Doc_Categ_ID
AND documenttype.Doc_Type_Name =#DocumentType
IF NOT EXISTS (SELECT Assoc_Orig_Tran_ID FROM [ECM].[Assoc_Orig_Tran_TXN] WHERE Assoc_Orig_Tran_ID=#AssociatedOriginatingTransactionID)
BEGIN
INSERT INTO [ECM].[ASsoc_Orig_Tran_TXN]
(Orig_Tran_Action_Rule_id, Assoc_Orig_Tran_ID, Assoc_Orig_Status_Code, First_Rule_Date, Final_Actionable_Date, Folder_ID,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#RuleID,#AssociatedOriginatingTransactionID, 'PEND', #EffectiveOrCreationDate, #FinalDate,NULL,GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
END
IF NOT EXISTS (SELECT originating_tran_id FROM ecm.bundle_checklist_txn WHERE originating_tran_id = #OriginatingTransactionID AND bundle_name = #BundleName)
BEGIN
INSERT INTO [ECM].[Bundle_Checklist_TXN]
( Bundle_Action_Rule_ID,Bundle_Name,Bundle_Status_Code,ASsoc_Orig_Tran_ID,Originating_Tran_ID,Doc_Categ_Name, Next_Action_Dt,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#RuleID,#BundleName,'PEND',#AssociatedOriginatingTransactionID,#OriginatingTransactionID,#DocumentCategory,#FinalDate,GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
END
IF NOT EXISTS (SELECT t.Doc_Checklist_TXN_ID FROM (SELECT bundlechecklist.Bundle_TXN_ID, documentchecklist.Doc_Checklist_TXN_ID, documentchecklist.Doc_Type_Name FROM ecm.bundle_checklist_txn bundlechecklist
LEFT OUTER JOIN [ECM].[Document_Checklist_TXN] documentchecklist ON documentchecklist.Bundle_TXN_ID = bundlechecklist.Bundle_TXN_ID
WHERE bundlechecklist.originating_tran_id = #OriginatingTransactionID AND bundle_name = #BundleName)t WHERE t.Doc_Checklist_TXN_ID is not null )
BEGIN
SELECT #BundleTransactionID=bundlechecklist.bundle_txn_id FROM [ECM].[Bundle_Checklist_TXN] bundlechecklist
INSERT INTO [ECM].[Document_Checklist_TXN]
(bundle_txn_id, document_action_rule_id, action_rule_name, doc_type_name, cp_document_name, document_id, doc_status_code,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#BundleTransactionID, #RuleID, #RuleName, #DocumentType, #DocumentName, #DocumentID, 'PEND',GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
END
END
END
END
In my code, if I execute with values, its not working and and insert fails
with the following error :
Msg 515, Level 16, State 2, Procedure usp_CreateChecklist, Line 95
Cannot insert the value NULL into column 'Orig_Tran_Action_Rule_id',
table 'EIC_ECM_Checklist.ECM.Assoc_Orig_Tran_TXN'; column does not
allow nulls. INSERT fails. The statement has been terminated.
Msg 515, Level 16, State 2, Procedure usp_CreateChecklist, Line 104
Cannot insert the value NULL into column 'Bundle_Action_Rule_ID',
table 'EIC_ECM_Checklist.ECM.Bundle_Checklist_TXN'; column does not
allow nulls. INSERT fails. The statement has been terminated.
Msg 515, Level 16, State 2, Procedure usp_CreateChecklist, Line 117
Cannot insert the value NULL into column 'Document_Action_Rule_ID',
table 'EIC_ECM_Checklist.ECM.Document_Checklist_TXN'; column does not
allow nulls. INSERT fails. The statement has been terminated.
But if I execute individually each line and its working and all values getting stored in the table. All insert statement works. Tried debugging with individual statement. Like below :
SELECT
DATEADD(DAY, Number_Of_Days_Till_Next_Action, '2015-10-18T00:00:00'),
rule1.Action_Rule_ID, rule1.Action_Rule_Name,
rule1.Current_Action_ID
FROM
ecm.Action_Rule rule1
INNER JOIN
ecm.Action_Rule_Group rulegroup ON rulegroup.Action_Rule_Group_ID = rule1.Action_Rule_Group_ID
INNER JOIN
ref.Line_of_Business lob ON lob.Line_of_Business_Code = rulegroup.Line_of_Business_Code
INNER JOIN
ref.State state ON state.State_Alpha_Code=rulegroup.State_Alpha_Code
INNER JOIN
ref.Source_System sourcesystem ON sourcesystem.Source_System_ID = rulegroup.Source_System_ID
INNER JOIN
ecm.[Document Catgeory] documentcategory ON documentcategory.Doc_Categ_ID = rulegroup.Doc_Categ_ID
INNER JOIN ecm.[Document Type] documenttype ON documenttype.Doc_Type_ID=rule1.Doc_Type_ID
INNER JOIN ecm.Exec_Acct_Group occupationgroup ON occupationgroup.Exec_Acct_Grp_ID = rulegroup.Exec_Acct_Grp_ID
INNER JOIN [ECM].[Bundle] bundle ON bundle.Bundle_ID = rule1.Bundle_ID
WHERE
bundle.Bundle_Name = 'Auto'
AND rulegroup.Line_of_Business_Code='A'
AND rulegroup.State_Alpha_Code='FL'
AND documentcategory.Doc_Categ_Name=' review'
AND rulegroup.Exec_Acct_Grp_ID=2
AND rule1.Transaction_Flow='Outgoing doc'
AND sourcesystem.Source_System_Name = 'V4 Policy'
AND rulegroup.Doc_Categ_ID=documentcategory.Doc_Categ_ID
AND documenttype.Doc_Type_Name ='Application'
SELECT Assoc_Orig_Tran_ID FROM [ECM].[Assoc_Orig_Tran_TXN] WHERE Assoc_Orig_Tran_ID='BPA201607131452113541050525A1REN'
INSERT INTO [ECM].[ASsoc_Orig_Tran_TXN]
(Orig_Tran_Action_Rule_id, ASsoc_Orig_Tran_ID, ASsoc_Orig_Status_Code, First_Rule_Date, Final_Actionable_Date, Folder_ID,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
('157','BPA201607131452113541050525A1REN', 'PEND','2015-10-18T00:00:00' , '2015-11-07 00:00:00.000',NULL,GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
SELECT originating_tran_id FROM ecm.bundle_checklist_txn WHERE originating_tran_id = 'BPA201607131452113541050525A1REN' AND bundle_name = 'Auto'
INSERT INTO [ECM].[Bundle_Checklist_TXN]
( Bundle_Action_Rule_ID,Bundle_Name,Bundle_Status_Code,ASsoc_Orig_Tran_ID,Originating_Tran_ID,Doc_Categ_Name, Next_Action_Dt,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
('157','Auto','PEND','BPA201607131452113541050525A1REN','BPA201607131452113545050525A1AMD','Underwriting review','2015-11-07 00:00:00.000',GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
declare #BundleTransactionID int
SELECT #BundleTransactionID=bundlechecklist.bundle_txn_id FROM [ECM].[Bundle_Checklist_TXN] bundlechecklist
INSERT INTO [ECM].[Document_Checklist_TXN]
(bundle_txn_id, document_action_rule_id, action_rule_name, doc_type_name, cp_document_name, document_id, doc_status_code,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#BundleTransactionID, '157', 'FL Application', 'Application', 'CPLProp_Acknowledgment_FAQs', '321Z01W_007624ZRM00002G', 'PEND',GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
Any idea where it fails?
First Error says that you are trying to insert null value to Orig_Tran_Action_Rule_id but this field is NOT NULL so u cannot insert the data.
INSERT INTO [ECM].[ASsoc_Orig_Tran_TXN]
(Orig_Tran_Action_Rule_id, Assoc_Orig_Tran_ID, Assoc_Orig_Status_Code, First_Rule_Date, Final_Actionable_Date, Folder_ID,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#RuleID,#AssociatedOriginatingTransactionID, 'PEND', #EffectiveOrCreationDate, #FinalDate,NULL,GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
Please check #RuleID.
And for other two also the same issue.
And you are right, when you insert individual at that time you provide values('157') instead of Variables(#RuleID).
So it works fine.

sql trigger - restrict by time

I want this trigger to work only between a certain time and another time (say 6am-10pm). please help!
ALTER TRIGGER [db].[el] ON [Reports].[db].[stat]
AFTER INSERT, UPDATE
AS
SET NOCOUNT ON;
INSERT INTO [Reports].[db].[el]
(
[StationID]
,[Count]
)
SELECT i.StationID,
i.[EmptyDockCount],
GETDATE(),
NULL,
NULL,
i.[LastUpdateDate],
FROM INSERTED i
INNER JOIN DELETED d
on d.StationID = i.StationID
INNER JOIN DBOS.dbo.StationDim bsd
ON bsd.StationID = i.StationID
WHERE i.[Count] = 0
AND d.[count] <> 0
;
Try like this,
This is the key statement CONVERT(TIME, Getdate()) BETWEEN '6:00:00.0000000' AND '22:00:00.0000000'
ALTER TRIGGER [db].[el]
ON [Reports].[db].[stat]
AFTER INSERT, UPDATE
AS
SET NOCOUNT ON;
IF CONVERT(TIME, Getdate()) BETWEEN '6:00:00.0000000' AND '22:00:00.0000000'
BEGIN
INSERT INTO [Reports].[db].[el]
([StationID],
[Count])
SELECT i.StationID,
i.[EmptyDockCount],
Getdate(),
NULL,
NULL,
i.[LastUpdateDate]
FROM INSERTED i
INNER JOIN DELETED d
ON d.StationID = i.StationID
INNER JOIN DBOS.dbo.StationDim bsd
ON bsd.StationID = i.StationID
WHERE i.[Count] = 0
AND d.[count] <> 0
END;

SQL how to get an equality comparator on a list of ints

I'm writing an SQL query as follows:
ALTER proc [dbo].[Invoice_GetHomePageInvoices] (
#AreaIdList varchar(max)
, #FinancialYearStartDate datetime = null
, #FinancialYearEndDate datetime = null
) as
set nocount on
select *
from Invoice i
left outer join Organisation o on i.OrganisationId = o.Id
left outer join Area a on i.AreaId = a.Id
where i.InvoiceDate BETWEEN #FinancialYearStartDate AND #FinancialYearEndDate
The #AreaIdList parameter is going to be in the format "1,2,3" etc.
I'm wanting to add a line which will only return invoices who have area id equal to any of the ids in #AreaIdList.
I know how to do a statement if it was on areaId to search on ie. where i.AreaId == areaId problem is now I have this list I got to compare for every area Id in #AreaIdList.
Can anybody tell me how you would go about this?
Unpack your ID list to a table and use where AreadID in (select ID from ...)
ALTER proc [dbo].[Invoice_GetHomePageInvoices] (
#AreaIdList varchar(max)
, #FinancialYearStartDate datetime = null
, #FinancialYearEndDate datetime = null
) as
set nocount on
set #AreaIdList = #AreaIdList+','
declare #T table(ID int primary key)
while len(#AreaIdList) > 1
begin
insert into #T(ID) values (left(#AreaIdList, charindex(',', #AreaIdList)-1))
set #AreaIdList = stuff(#AreaIdList, 1, charindex(',', #AreaIdList), '')
end
select *
from Invoice i
left outer join Organisation o on i.OrganisationId = o.Id
left outer join Area a on i.AreaId = a.Id
where i.InvoiceDate BETWEEN #FinancialYearStartDate AND #FinancialYearEndDate and
i.AreadID in (select ID from #T)

Resources