triggers are not firing when I use bulk copy in code - sql

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 ?

Related

SQL Stored Procedure Parameter set to Uppercase

I want to force a user's string input in a stored procedure to uppercase. I tried writing UPPER prior to the #parameterName but I got a syntax error. Is this possible? Would be it be better suited to convert the string to uppercase in the statement itself? Here's the code to my SP where I was attempting to use UPPER in the parameter definition.
ALTER PROCEDURE [dbo].[UpdateEntries]
UPPER #ENTRY_TYPE NVARCHAR(20) = '',
UPPER #ENTRY_NAME NVARCHAR(50),
#CLASS_TYPE_ID INT,
#ENTRY_PRICE DEC(4,2),
#ENTRY_DESCRIPT NVARCHAR(max),
#PET_FRIENDLY BIT,
#AGE_RESTRICTION BIT,
#PRICE_RANGE_ID INT,
#RESTAURANT_TYPE_ID INT NULL
AS
BEGIN
SET NOCOUNT ON;
IF #ENTRY_TYPE = 'ACTIVITY'
BEGIN
UPDATE ACTIVITY_DETAIL
SET ACT_NAME = #ENTRY_NAME,
ACT_PRICE = #ENTRY_PRICE,
ACT_DESCRIPT = #ENTRY_DESCRIPT,
ACT_DOG_FRIENDLY = #PET_FRIENDLY,
ACT_AGE_RESTRICTION = #AGE_RESTRICTION,
ACT_PRICE_RANGE_ID = #PRICE_RANGE_ID
WHERE NOT EXISTS (SELECT 1 FROM dbo.[ACTIVITY_DETAIL] WHERE ACT_NAME = #ENTRY_NAME);
END
IF #ENTRY_TYPE = 'BUSINESS'
BEGIN
UPDATE BUSINESS_DETAIL
SET BUSINESS_NAME = #ENTRY_NAME,
BUSINESS_PRICE = #ENTRY_PRICE,
BUSINESS_DESCRIPT = #ENTRY_DESCRIPT,
BUSINESS_DOG_FRIENDLY = #PET_FRIENDLY,
BUSINESS_PRICE_RANGE_ID = #PRICE_RANGE_ID
WHERE NOT EXISTS (SELECT 1 FROM dbo.[BUSINESS_DETAIL] WHERE BUSINESS_NAME = #ENTRY_NAME);
END
IF #ENTRY_TYPE = 'HOTEL'
BEGIN
UPDATE HOTEL_DETAIL
SET HOTEL_NAME = #ENTRY_NAME,
HOTEL_PRICE = #ENTRY_PRICE,
HOTEL_DESCRIPT = #ENTRY_DESCRIPT,
HOTEL_PET_FRIENDLY = #PET_FRIENDLY,
HOTEL_PRICE_RANGE_ID = #PRICE_RANGE_ID
WHERE NOT EXISTS (SELECT 1 FROM dbo.[HOTEL_DETAIL] WHERE HOTEL_NAME = #ENTRY_NAME);
END
IF #ENTRY_TYPE = 'RESTAURANT'
BEGIN
UPDATE RESTAURANT_DETAIL
SET RESTAURANT_NAME = #ENTRY_NAME,
RESTAURANT_PRICE_AVG = #ENTRY_PRICE,
RESTAURANT_DESCRIPT = #ENTRY_DESCRIPT,
RESTAURANT_DOG_FRIENDLY = #PET_FRIENDLY,
RESTAURANT_PRICE_RANGE_ID = #PRICE_RANGE_ID
WHERE NOT EXISTS (SELECT 1 FROM dbo.[RESTAURANT_DETAIL] WHERE RESTAURANT_NAME = #ENTRY_NAME);
END
END
UPPER #ENTRY_TYPE NVARCHAR(20) = '',
UPPER #ENTRY_NAME NVARCHAR(50),
These are wrong. No such usage.
#ENTRY_TYPE NVARCHAR(20) = '',
#ENTRY_NAME NVARCHAR(50),
SELECT #ENTRY_TYPE = UPPER(#ENTRY_TYPE);
SELECT #ENTRY_NAME = UPPER(#ENTITY_NAME);

SQL Server 2008 - insert trigger not firing

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!

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

SQL if else stored procedure

I'm writing a stored procedure and it's working for if but not for else. For if I'm getting the correct ID value but for else it's just giving me null.
SELECT #ID = ID FROM PRODUCTS WHERE SN = #SN
SELECT #Chip_ID = Chip_ID FROM PRODUCTS WHERE SN = #SN
SELECT #Power = Power From Module_Cycle WHERE ChipID = #Chip_ID
SELECT #Test_ID=Test_ID FROM TestEE_Mod WHERE ID=#ID AND #TypeID = TypeID
IF(#Test_ID IS NOT NULL)
BEGIN
IF(#TypeID = '3')
BEGIN
SELECT #Temp_TestID=TestID FROM TempCycle WHERE ChipID = #Chip_ID AND #Power = 'false'
BEGIN
UPDATE TestEE_Mod SET Temp_TestID = #Temp_TestID WHERE ID = #ID AND TypeID = #TypeID
END
END
ELSE
BEGIN
SELECT #Temp_TestID=TestID FROM TempCycle WHERE ChipID = #Chip_ID AND #Power = 'true'
BEGIN
UPDATE TestEE_Mod SET Temp_TestID = #Temp_TestID WHERE ID = #ID AND TypeID = #TypeID
END
END
END
Most likely the issue lies in the #Power variable. In your two SELECT statements, the only difference is that one includes #Power = 'false' in the WHERE clause, while the other includes #Power = 'true'.
Since #Power is a variable, not an actual column in your TempCycle table, I'm guessing you actually meant to filter by Power = #Power in both of them.

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