I am new in SQL server and having trouble with this trigger code. Can you please tell me what is wrong with this line: set NazivFirme=(select NazivFirme from inserted)... This is where I get an error.
USE [BazaPreduzece]
GO
/****** Object: Trigger [dbo].[promenaNazivaFirme] Script Date: 2017-03-28 5:29:47 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER trigger [dbo].[promenaNazivaFirme]
on [dbo].[Firma]
AFTER UPDATE
as
declare #FirmaID int
select #FirmaID=FirmaID from inserted
if update (NazivFirme)
begin
alter table Vlasnik disable trigger zabranaAzuriranjaNazivaFirme
update [dbo].[Vlasnik]
set NazivFirme=(select NazivFirme from inserted)
where FirmaID=#FirmaID
alter table Vlasnik enable trigger zabranaAzuriranjaNazivaFirme
end
That's theFirma and the Vlasnik tables...
Related
I'm trying to rename columns in a table for which there is a trigger. I've used SQL > Refactor > Rename to rename the column. And the trigger file also gets updated. However, when I publish, I get this:
Procedure TR_accrual_Accrual_Update, Line 134 Invalid column name
'MinHoursRule'.
That's the old column name. I'm assuming the publish is updating the table first, and sees that the current/old trigger still has the old column name.
Is it possible to rename a column, update the trigger, and publish?
The only solution I can really think of is to do this:
Delete the triggers and publish
Rename the columns
Add the triggers again
Publish
This is what I did as a work-around:
Add the new columns
Leave the old columns
Have the trigger use both sets of columns
Publish/deploy to prod soon
Remove the old columns
Publish/deploy to prod later
So, instead of renaming, I just created new columns, and then eventually deleted the old ones.
Yuck. But it worked.
Note: In our C# domain models, I only reference the new columns.
I guess that you have something wrong with the publish profile settings. You might have something disabled, for example "Do not modify triggers" or something like that. I just created new SSDT project in VS 2019 with following structure:
CREATE TABLE [dbo].[test]
(
[Id] INT ,
b int
)
GO
CREATE TRIGGER [dbo].[Trigger_test]
ON [dbo].[test]
FOR DELETE, INSERT, UPDATE
AS
BEGIN
SET NoCount ON
insert into test2 select b from inserted
END
GO
CREATE TABLE [dbo].[test2]
(
a int
)
GO
Published the project with default settings to the new database and made single insert to the dbo.test table. Made sure that there is record in dbo.test2 table. After that I re-factored dbo.test.b column to dbo.test.a then published again and everything worked. This is generated script:
/*
Deployment script for trg_test
This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/
GO
SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;
SET NUMERIC_ROUNDABORT OFF;
GO
:setvar DatabaseName "trg_test"
:setvar DefaultFilePrefix "trg_test"
:setvar DefaultDataPath ""
:setvar DefaultLogPath ""
GO
:on error exit
GO
/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF;
*/
:setvar __IsSqlCmdEnabled "True"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
BEGIN
PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
SET NOEXEC ON;
END
GO
USE [$(DatabaseName)];
GO
PRINT N'The following operation was generated from a refactoring log file 80d0e5de-e188-465e-b83c-18f38a1cec98';
PRINT N'Rename [dbo].[test].[b] to a';
GO
EXECUTE sp_rename #objname = N'[dbo].[test].[b]', #newname = N'a', #objtype = N'COLUMN';
GO
PRINT N'Altering Trigger [dbo].[Trigger_test]...';
GO
ALTER TRIGGER [dbo].[Trigger_test]
ON [dbo].[test]
FOR DELETE, INSERT, UPDATE
AS
BEGIN
SET NoCount ON
insert into test2 select a from inserted
END
GO
-- Refactoring step to update target server with deployed transaction logs
IF OBJECT_ID(N'dbo.__RefactorLog') IS NULL
BEGIN
CREATE TABLE [dbo].[__RefactorLog] (OperationKey UNIQUEIDENTIFIER NOT NULL PRIMARY KEY)
EXEC sp_addextendedproperty N'microsoft_database_tools_support', N'refactoring log', N'schema', N'dbo', N'table', N'__RefactorLog'
END
GO
IF NOT EXISTS (SELECT OperationKey FROM [dbo].[__RefactorLog] WHERE OperationKey = '80d0e5de-e188-465e-b83c-18f38a1cec98')
INSERT INTO [dbo].[__RefactorLog] (OperationKey) values ('80d0e5de-e188-465e-b83c-18f38a1cec98')
GO
GO
PRINT N'Update complete.';
GO
I have several databases with similar structures on several servers. I have a job who drop a table and recreate it in the night for every database. But I had a problem with only one database on one server :
Invalid value given for parameter #procmapid. Specify a valid
parameter value.
I made some research and I have seen that the problem was because the trigger tr_MStran_droptable was enabled. So I disable it and now it works. But on my other database this trigger is enabled too and I can drop the table.
How it is possible? I can't find this trigger structure to study it in the database too. Did somebody know more about the trigger tr_MStran_droptable?
Trigger code :
CREATE TRIGGER [tr_MStran_droptable] ON DATABASE
FOR DROP_TABLE AS
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET NUMERIC_ROUNDABORT OFF
SET QUOTED_IDENTIFIER ON
DECLARE #EventData XML
SET #EventData = EventData()
IF object_id('dbo.sysarticles') IS NULL
OR object_id('dbo.syspublications') IS NULL
OR object_id('dbo.sysextendedarticlesview') IS NULL
OR EXISTS (
SELECT 1
FROM #EventData.nodes('/EVENT_INSTANCE') AS R(event_instance)
WHERE lower(event_instance.value('SchemaName[1]', 'sysname')) IN (
N'sys'
,N'cdc'
)
OR lower(event_instance.value('ObjectName[1]', 'sysname')) IN (
N'sysextendedarticlesview'
,N'sysarticles'
,N'syspublications'
)
OR event_instance.value('ObjectName[1]', 'sysname') LIKE N'#%'
)
RETURN
EXEC sys.sp_MStran_ddlrepl #EventData
,5
GO
DISABLE TRIGGER [tr_MStran_droptable] ON DATABASE
GO
It's Because of the trigger :
The trigger is to keep replication alive so :
Try running sp_removedbreplication 'CurrentDatabase' that will remove replication
or
Disable Trigger : DISABLE TRIGGER [tr_MStran_droptable] ON DATABASE
I have two data base in same server TEST1 and TEST2
In TEST1 i have a table called dbo.TB_EVENT_LOG
columns are
[nEventLogIdn]
[nDateTime]
[nReaderIdn]
[nEventIdn]
[nUserID]
[nIsLog]
[nTNAEvent]
[nIsUseTA]
[nType]
and in Test2 i have a table called dbo.AccessLog
columns are
[RCDID]
[EmployeeID]
[LogDate]
[LogTime]
[TerminalID]
[InOut]
What i want to do is fire a trigger when ever any data is inset or update to test1 dbo.TB_EVENT_LOG. And insert the data from specific columns of dbo.TB_EVENT_LOG( nDateTime, nReaderIdn, nUserID) to dbo.AccessLog (LogDate, TerminalID, EmployeeID)
The trigger running in dbo.TB_EVENT_LOG Table
Here is the trigger code i have so far
USE [test1]
GO
/****** Object: Trigger [dbo].[coveter] Script Date: 11/18/2018 2:25:13 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
-- Create date: 18/11/2018
-- Description:
-- =============================================
ALTER TRIGGER [dbo].[coveter]
ON [dbo].[TB_EVENT_LOG]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
insert into test2.dbo.AccessLog
(
[LogDate],
[LogTime],
[TerminalID],
[EmployeeID]
)
select [nDateTime], [nDateTime], [nReaderIdn],[nUserID] from dbo.TB_EVENT_LOG
END
The Code run without any error but i couldn't get the result i want. Any help?
Thank you in advance.
This code:
USE [db]
GO
/****** Object: UserDefinedFunction [dbo].[GetFieldPickerReports] Script Date: 01/11/2013 19:12:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[GetFieldPickerReports] (#CustomerName varchar(100))
RETURNS TABLE
AS
RETURN SELECT [fpr].[ID], [fpr].[Name], [fpr].[Global], [fpr].[FPRCategoryID]
FROM FieldPickerReport fpr, dbo.GetProductKeyIdByCustomer(#CustomerName) pk
LEFT JOIN [FPRCategory] fprcat on ([fpr].[FPRCategoryID]=[fprcat].[ID])
WHERE [Global]=1 OR ProductKeyID=pk.id
Produces an error:
The multi-part identifier "fpr.FPRCategoryID" could not be bound.
This query works without the Left Join (which I currently need to add) or either with the removal of dbo.GetProductKeyIdByCustomer() and the Where clause.
Here's the code for dbo.GetProductKeyIdByCustomer()
USE [db]
GO
/****** Object: UserDefinedFunction [dbo].[GetProductKeyIdByCustomer] Script Date: 01/11/2013 19:58:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[GetProductKeyIdByCustomer] (#CustomerName varchar(100))
RETURNS TABLE
AS
RETURN SELECT id
FROM ProductKey
WHERE [CustomerName]=#CustomerName AND Enabled=1
What is wrong with my query?
First, I think that these UDFs would be better implemented as Views.
Second, you are mixing implicit and explicit joins. Using all explicit joins should solve your issue:
SELECT
[fpr].[ID],
[fpr].[Name],
[fpr].[Global],
[fpr].[FPRCategoryID]
FROM
FieldPickerReport fpr
JOIN dbo.GetProductKeyIdByCustomer(#CustomerName) pk
ON [Global] = 1 OR ProductKeyID = pk.id
LEFT JOIN FPRCategory fprcat
ON fpr.FPRCategoryID = fprcat.ID
I have a trigger that is firing with out issue in non-production but the same exact code is failing to fire in production. I've confirmed it's not disabled and I've done a trace to see that it is not even executing in production.. I've checked the relevant OBJECTPROPERTY elements and they are the same. I've confirm the code is the same. I've confirmed the same inserts are coming from the application. Below is the code for this trigger:
/******
Object: Trigger [dbo].[tr_trigger_ins]
Script Date: 06/02/2012 16:51:51
******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE TRIGGER [dbo].[tr_trigger_ins] ON [dbo].[table_1]
FOR INSERT
AS
BEGIN
UPDATE table_2
SET col_1 =
CASE
WHEN i.col_2 = '0' THEN 0 ELSE 1
END
FROM INSERTED i
INNER JOIN table_3 pa
ON i.col_3 = pa.col_3 AND pa.col_4 = 'ispublic'
INNER JOIN table_4 pp
ON i.col_5 = pp.col_5
INNER JOIN table_2 cs
ON pp.col_6 = cs.col_6
END
GO
Below is a trigger that is an instead of insert on the same table that is executing in both environments:
/******
Object: Trigger [dbo].[tr_trigger_before_ins]
Script Date: 06/02/2012 16:55:52
******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE TRIGGER [dbo].[tr_trigger_before_ins] ON [dbo].[table_1]
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO table_1
SELECT * FROM INSERTED
WHERE col_3 in (73, 199)
END
GO
Any help is greatly appreciated.
First make sure the trigger hasn't been disabled:
ENABLE Trigger tr_trigger_ins ON dbo.table_1;
GO
Ultimately it came down to the issue of replication. Transactions flowed over in a different order than expected. Once we accommodated for this in the trigger logic it worked well.