SQL Server 2008 - insert trigger not firing - sql

I have a VB.NET application that is creating some INSERT, UPDATE, DELETE statements based on the users selections. I can tell that the SQL is being successfully executed on SQL Server 2008 (I see the table records adjusting appropriately), except one of my insert triggers is not firing.
SQL generated by the application code:
insert into [RECLASS_BALANCE_ADJSTMNT]( PRGRM_REC_ID, DEDUCTN_REC_ID, RBA_YR_PD_NUM, RBA_AMOUNT, RBA_TYPE, ADJUSTER_USER_ID )
values (5504, 8154, dbo.getCurrentYrPdNum(), abs(-21510.70), 'M', '10139638');
insert into [MATCH] (DEDUCTN_REC_ID, PRGRM_REC_ID, YR_PD_NUM, MATCH_TYPE_FLG)
values (8154, 5504, dbo.getCurrentYrPdNum(), 'M');
delete from [POTENTIAL_MATCH]
where deductn_rec_id = 8154
and prgrm_rec_id = 5504;
update [PROGRAM_GL_DTL]
set MATCH_FLG = 'Y', MATCH_FLG_MODIFIED_TIMESTAMP = getdate()
where PRGRM_REC_ID = 5504;
update [DEDUCTION]
set MATCH_FLG = MATCH_FLG + 1
where DEDUCTN_REC_ID = 8154;
INSERT trigger:
CREATE TRIGGER [dbo].[check_partial_offset_status]
ON [dbo].[RECLASS_BALANCE_ADJSTMNT]
FOR INSERT
AS
BEGIN
DECLARE #deductnRecId int;
DECLARE #deductnBalance decimal(18,2);
DECLARE #deductnOriginalAmount decimal(18,2);
SELECT #deductnRecId = i.deductn_rec_id FROM inserted i;
SELECT #deductnBalance = ds.ytd_amt, #deductnOriginalAmount = ds.original_invoice_amount
FROM deduction_summary_updt ds
WHERE ds.deductn_rec_id = #deductnRecId;
IF ABS(#deductnBalance) > 0
BEGIN
UPDATE deduction
SET comment_id = 12
WHERE deductn_rec_id = #deductnRecId;
END --partial matched
IF #deductnBalance = #deductnOriginalAmount
BEGIN
UPDATE deduction
SET comment_id = 6
WHERE deductn_rec_id = #deductnRecId;
END --unmatched
IF #deductnBalance = 0
BEGIN
UPDATE deduction
SET comment_id = 9
WHERE deductn_rec_id = #deductnRecId;
END --fully matched
DECLARE #prgrmRecId int;
DECLARE #prgrmBalance decimal(18,2);
DECLARE #prgrmOriginalAmount decimal(18,2);
SELECT #prgrmRecId = i.prgrm_rec_id FROM inserted i;
SELECT #prgrmBalance = rs.ytd_amt, #prgrmOriginalAmount = rs.reclass_amount
FROM reclass_summary rs
WHERE rs.prgrm_rec_id = #prgrmRecId;
IF ABS(#prgrmBalance) > 0
BEGIN
UPDATE program_gl_dtl
SET comment_id = 12
WHERE prgrm_rec_id = #prgrmRecId;
END --partial matched
IF #prgrmBalance = #prgrmOriginalAmount
BEGIN
UPDATE program_gl_dtl
SET comment_id = 5
WHERE prgrm_rec_id = #prgrmRecId;
END --unmatched
IF #prgrmBalance = 0
BEGIN
UPDATE program_gl_dtl
SET comment_id = 10
WHERE prgrm_rec_id = #prgrmRecId;
END --fully matched
END
GO
I'm trying to understand why the "INSERT INTO [RECLASS_BALANCE_ADJSTMNT].." generated by the application code does not cause the trigger to fire.
I appreciate any help. Thanks!

Related

T-SQL 'IF' condition can not recognize column name

I am trying to execute this query with some 'conditional logic', it is my first attempt doing something like this in databases.
Here is the code:
DECLARE #iddevice INT;
SET #iddevice = 15;
IF(#iddevice = 15 AND DEVICEATTRIBUTES.DEVICEATTRIBUTE = 'PortA')
BEGIN
UPDATE DEVICEATTRIBUTES
SET VALUE = '4701'
WHERE IDDEVICE = 15 AND DEVICEATTRIBUTES.DEVICEATTRIBUTE = 'PortA'
END
IF(#iddevice = 15 AND DEVICEATTRIBUTES.DEVICEATTRIBUTE = 'PortB')
BEGIN
UPDATE DEVICEATTRIBUTES
SET VALUE = '4711'
WHERE IDDEVICE = 15 AND DEVICEATTRIBUTES.DEVICEATTRIBUTE = 'PortB'
END
IF(#iddevice = 15 AND DEVICEATTRIBUTES.DEVICEATTRIBUTE = 'IP')
BEGIN
UPDATE DEVICEATTRIBUTES
SET VALUE = '172.19.106.201'
WHERE IDDEVICE = 15 AND DEVICEATTRIBUTES.DEVICEATTRIBUTE = 'IP'
END;
GO
I am aware that something with the syntax is wrong, my question is ... how can I add DEVICEATTRIBUTES.DEVICEATTRIBUTE inside the 'if' clause?
You script you can re-write as follow:
DECLARE #iddevice INT;
SET #iddevice = 15;
UPDATE DEVICEATTRIBUTES
SET VALUE =
CASE
WHEN DEVICEATTRIBUTES.DEVICEATTRIBUTE = 'PortA' THEN '4701'
WHEN DEVICEATTRIBUTES.DEVICEATTRIBUTE = 'PortB' THEN '4711'
WHEN DEVICEATTRIBUTES.DEVICEATTRIBUTE = 'IP' THEN '172.19.106.201'
END
WHERE IDDEVICE = #iddevice AND DEVICEATTRIBUTES.DEVICEATTRIBUTE IN ('PortA', 'PortB', 'IP')
In SQL Server, you can use UPDATE with JOIN:
UPDATE DA
SET VALUE = '4701'
FROM DEVICEATTRIBUTES DA JOIN
(VALUES ('PortA', '4701'),
('PortB', '4711'),
('IP', '172.19.106.201')
) V(DEVICEATTRIBUTE, VALUE)
ON DA.DEVICEATTRIBUTE = V.DEVICEATTRIBUTE
WHERE IDDEVICE = 15;
The VALUES clause is a handy way to add in the values you want to change -- and it reduces the risk of typos.
However, in your code, you can just use three UPDATEs. The IF statements are not necessary. If no rows match the WHERE clause then no rows are updated.

Optimize the procedure in Informix

I need to optimize the Procedure below. Syntax should be in Informix.
Here a table update is required with sequential update. It seems to be very large.Can it be optimized.
CREATE OR REPLACE PROCEDURE ENTRY() LANGUAGE SQL
BEGIN ATOMIC
DECLARE record integer;
DECLARE txaa_id bigint;
DECLARE id bigint;
DECLARE createDatetimed timestamp;
DECLARE idPlus bigint;
set record = 0;--
set txaa_id = 0;--
set id = 0;--
set idPlus = 0;--
set createDatetimed = null;--
FOR v_row1 as select distinct txaa_id from finalBaseData
DO
FOR v_row2 as select txsa_id , finalBaseData.txaa_id , finalBaseData.createdatetime from tx_status_audit,finalBaseData where tx_status_audit.txaa_id = v_row1.txaa_id and tx_status_audit.txaa_id = finalBaseData.txaa_id and tx_status_audit.cdts = 'OUT' order by tx_status_audit.create_datetime desc fetch first 1 rows only
DO
set record = record + 1;
IF ( record = 1)
THEN
set id = v_row2.txsa_id;
set idPlus = id + 1;
set txaa_id = v_row2.txaa_id;
set createDatetimed = v_row2.createdatetime;
END IF;
END FOR;
insert into tx_status_audit values (idPlus,'CMPT',txaa_id,'HWNG',createDatetimed);
set record = 0;
set idPlus = 0;
set txaa_id = 0;
set createDatetimed = null;
END FOR;
END;

Uniqueidentifier as parameter in SQL Server Function

I have created a Function in SQL Server 2012 that I will use in a Check Constraint on a table.
The function works as expected if I do:
SELECT [dbo].[CheckValidCardnumberForShellTankingen] ('700678036658047691' ,'2925CA00-6DD5-4F9D-AB0E-AA15DBBD388B')
But when I try to set the expression in Check Constraint so:
([dbo].[CheckValidCardnumberForShellTankingen]([Volledig kaartnummer],[RollBackCode])=(1))
I get a Messaage: "Error validating constraint 'CK_MyConstraint'"
I use the Uniqueidentifier in a Where clause and the strange thing is if I replace the parameter with string containing the Uniqueidentifier I dont get this error.
Here is the Function:
-- =============================================
-- Author: Anders Pedersen
-- Create date: 2015-02-13
-- Description: Check of the Cardnumber of a transaction is valid.
-- =============================================
CREATE FUNCTION [dbo].[CheckValidCardnumberForShellTankingen]
(
-- Add the parameters for the function here
#Cardnumber NvarChar(50),
#RollBackCode NvarChar(200)
)
RETURNS BIT
AS
BEGIN
-- Declare the return variable here
DECLARE
#Result BIT
,#ResultLenght BIT
,#ResultPrefix BIT
,#CardLenght INT
,#SupplierID INT
,#UseCardnumber BIT
,#Prefix NvarChar(50)
-- Add the T-SQL statements to compute the return value here
SET #Result = 0
SET #ResultLenght = 0
SET #ResultPrefix = 0
SET #CardLenght = -1
SET #SupplierID = -1
SET #UseCardnumber = 0
SET #Prefix = ''
-- Get the UseCardnumber and the SupplierID
SELECT #UseCardnumber = C.UseCardNumber, #SupplierID = F.SupplierID
FROM Client C INNER JOIN
ClientFileUploads F ON C.ClientID = F.ClientID
WHERE F.RollBackCode = #RollBackCode
--WHERE F.RollBackCode = '2925CA00-6DD5-4F9D-AB0E-AA15DBBD388B'
-- Only carry out the check if the Client use Cards else set the check to True (1)
IF #UseCardnumber = 1
BEGIN
SELECT #CardLenght = [CardNumberLenght], #Prefix = ISNULL([Prefix],'') FROM [dbo].[Supplier] AS S WHERE S.SupplierID = #SupplierID
IF (#CardLenght IS NULL) OR (#CardLenght = 0)
BEGIN
SET #ResultLenght = 1
END
ELSE
BEGIN
IF (LEN(#Cardnumber) - #CardLenght)= 0
BEGIN
SET #ResultLenght = 1
END
ELSE
BEGIN
SET #ResultLenght = 0
END
END
IF SUBSTRING(#Cardnumber, 1, LEN(#Prefix)) = #Prefix
BEGIN
SET #ResultPrefix = 1
END
ELSE
BEGIN
SET #ResultPrefix = 0
END
IF ((#ResultLenght = 1) AND (#ResultPrefix = 1))
BEGIN
SET #Result = 1
END
ELSE
BEGIN
SET #Result = 0
END
END
ELSE
BEGIN
SET #Result = 1
END
-- Return the result of the function
RETURN #Result
END
GO
If #RollBackCode is a uniqueidentifier, I recommend making the parameter a uniqueidentifier and not a varchar.
As Rhys Jones points out, you shouldn't use a UDF in a check constraint.
See
https://dba.stackexchange.com/questions/22297/udf-in-check-constraint-downside
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/078b720f-faac-425c-b51a-33bcecb263d2/check-constraint-with-udf-problem-with-lots-of-data?forum=transactsql
http://sqlblog.com/blogs/tibor_karaszi/archive/2009/12/17/be-careful-with-constraints-calling-udfs.aspx
If you need to check in a trigger and roll back -- SQL Server - After Insert/ For Insert - Rollback

triggers are not firing when I use bulk copy in code

I have a trigger called "updateFriendlyURLTitle" in dbo.Aritcle table. When a individual article inserted, that trigger working fine.
But in article importing process: I've used the following codes. This codes make copy article but it doesn't fire the trigger to generate FriendlyUrl.
private void WriteArticlesToDatabase<TData>(DataSet ds, SqlTableDetails tableDetails, IEnumerable<TData> newArticles, SqlTransaction transaction)
{
var dt = WriteToDataTable(ds, tableDetails.Table, newArticles);
using (var bulkCopy = new SqlBulkCopy(_destConnection, SqlBulkCopyOptions.FireTriggers, transaction))
{
bulkCopy.DestinationTableName = tableDetails.ToString();
bulkCopy.WriteToServer(dt);
}
}
My trigger is like below:
ALTER TRIGGER [dbo].[updateFriendlyURLTitle] ON [dbo].[Articles]
AFTER INSERT, UPDATE
AS
IF ##ROWCOUNT > 0
BEGIN
IF COLUMNS_UPDATED() != 0x0000200000100000 -- columns other than newsCounterViews have been updated
BEGIN
DECLARE #oldestfulllucenebuild AS DATETIME
DECLARE #deletedNewsID INT
DECLARE #newsStatus BIT
DECLARE #maxcalcimp AS FLOAT
DECLARE #insertedCalculatedImportance INT
DECLARE #insertedNormalisedCalculatedImportance INT
DECLARE #insertedSeoURLTitle VARCHAR(255)
select #oldestfulllucenebuild = min(luceneIndexCreatedDate)
from Lucene_Indexes
where luceneIndexType = 'news'
select #oldestfulllucenebuild = dateAdd(year,10,#oldestfulllucenebuild)
select #maxcalcimp = cast(#oldestfulllucenebuild as float) * 48 *100 --the max importance
select #insertedCalculatedImportance = inserted.newsCalculatedImportance,
#insertedNormalisedCalculatedImportance = inserted.newsNormalisedCalculatedImportance,
#insertedSeoURLTitle = inserted.newsSeoURLTitle
from inserted
--if the current statement is updating the importance or seo columns then do not perform this query (so it doesn't get stuck in a loop)
IF (NOT UPDATE(newsCalculatedImportance)) AND (NOT UPDATE(newsNormalisedCalculatedImportance)) AND (NOT UPDATE(newsSeoURLTitle))
OR
--if it is inserting a new record then perform the query
(#insertedCalculatedImportance = 0 AND #insertedNormalisedCalculatedImportance is null AND #insertedSeoURLTitle = '')
BEGIN
update Articles
set newsCalculatedImportance = cast(cast(inserted.newsArticledate as float )*48 + inserted.newsimportance AS int)
, newsNormalisedCalculatedImportance = (1/ #maxcalcimp) * cast(cast(inserted.newsArticledate as float )*48 + inserted.newsimportance AS int)
, newsSeoURLTitle = LEFT(dbo.getSEOURLTitle(inserted.newstitle), 255)
from Articles inner join inserted on
Articles.newsid = inserted.newsid
END
SELECT #deletedNewsID = newsID, #newsStatus = newsStatus
FROM inserted
IF(#newsStatus = 0)
BEGIN
DELETE FROM tbl_DenormalisedNews WHERE newsid = #deletedNewsID
DELETE FROM News_Deleted_DateTime
WHERE NewsID = #deletedNewsID
INSERT INTO News_Deleted_DateTime
VALUES (#deletedNewsID, getDate())
END
ELSE
BEGIN
--news status is 1, remove it from the news_deleted_datetime table if it exists
DELETE FROM News_Deleted_DateTime
WHERE NewsID = #deletedNewsID
END
-- newsImage1 optimisation: if newsImage1 = '' THEN has_image = FALSE ELSE has_image = TRUE
IF UPDATE(newsImage1)
UPDATE Articles SET
has_image = CASE WHEN Articles.newsImage1 = '' THEN CAST(0 AS bit) ELSE CAST(1 AS bit) END
FROM
Articles INNER JOIN inserted ON Articles.newsid = inserted.newsid
END
END
Does anyone knows how to fix this issue ?

An object or column name is missing or empty

I am getting the following error
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Add a name or single space as the alias name.
for the query show below:
CREATE PROC [dbo].[Sp_Table1] #ctlg_ipt_event_id int
AS
SET NOCOUNT ON
DECLARE #current_status NCHAR(1), #ready_status_code NCHAR(1)
DECLARE #current_action NCHAR(1), #ready_action_code NCHAR(1), #done_action_code NCHAR(1)
DECLARE #pst_user_id int
SELECT #current_status = status_code
,#current_action = action_code
,#pst_user_id = last_mod_user_id
FROM merch_ctlg_ipt_event
WHERE ctlg_ipt_event_id = #ctlg_ipt_event_id
Select #ready_status_code = 'o'
, #ready_action_code = 'a'
, #done_action_code = 'b'
IF #current_status <> #ready_status_code OR #current_action <> #ready_action_code
BEGIN
RETURN
END
BEGIN TRAN
declare #rows int
,#err int
,#i int
,#name nvarchar(50) --COLLATE SQL_AltDiction_Pref_CP850_CI_AS
,#resolved_View_Name_category_id int
,#xref_value int
,#availability_start_date datetime
,#availability_end_date datetime
,#status_code int
,#last_mod_user_id int
,#CT datetime
,#supplier_id int
,#View_Name_id int
select #i = 1
,#CT = current_timestamp
Select Distinct mc.name,
mc.resolved_View_Name_category_id,
mc.xref_value,
mc.availability_start_date,
mc.availability_end_date,
mc.status_code,
CASE WHEN mc.last_mod_user_id = 42
THEN #pst_user_id
ELSE mc.last_mod_user_id
END as last_mod_user_id,
CURRENT_tsp
,IDENTITY(int,1,1) as rn
,si.supplier_id
,si.View_Name_id
into #temp
FROM View_Name AS si
JOIN merch_ctlg_ipt_View_Name AS mc
ON mc.supplier_id = si.supplier_id
AND mc.resolved_View_Name_id = si.View_Name_id
AND mc.cat_imp_event_id = #ctlg_ipt_event_id
AND mc.accept_flag = 'y'
WHERE si.shipper_flag = 'n'
select #rows=##ROWCOUNT,#err=##error
if #rows > 0 and #err=0
Begin
While #i <=#rows
begin
SElect #name = name,
#resolved_View_Name_category_id = resolved_View_Name_category_id,
#xref_value = xref_value,
#availability_start_date = availability_start_date,
#availability_end_date = availability_end_date,
#status_code = mc.status_code,
#last_mod_user_id =last_mod_user_id ,
,#i=#i+1
,#supplier_id=supplier_id
,#View_Name_id=View_Name_id
from #temp
Where rn=#i
UPDATE View_Name
SET name = #name,
View_Name_category_id = #resolved_View_Name_category_id,
xref_value = #xref_value,
availability_start_date = #availability_start_date,
availability_end_date = #availability_end_date,
status_code = #status_code,
last_mod_user_id = #last_mod_user_id ,
last_mod_timestamp = #CT
Where #sup_id = supplier_id
AND #View_Name_id = View_Name_id
AND shipper_flag = 'n'
IF ##ERROR > 0
BEGIN
ROLLBACK TRAN
RETURN
END
End
End
UPDATE
merch_ctlg_ipt_event
SET action_code = #done_action_code,
last_mod_timestamp = #CT
WHERE ctlg_ipt_event_id = #ctlg_ipt_event_id
IF ##ERROR > 0
BEGIN
ROLLBACK TRAN
RETURN
END
COMMIT TRAN
Return
go
Could you please help ?
You have 2 commas in a row here
#last_mod_user_id =last_mod_user_id ,
,#i=#i+1
Also probably not relevant to the error message but you have a line
Where #sup_id = supplier_id
but the declared variable is #supplier_id