Trigger Not Putting Data in History Table - sql-server

I have the following trigger (along with others on similar tables) that sometimes fails to put data into the historic table. It should put data into a historic table exactly as it's inserted/updated and stamped with a date.
CREATE TRIGGER [dbo].[trig_UpdateHistoricProductCustomFields]
ON [dbo].[productCustomFields]
AFTER UPDATE,INSERT
AS
BEGIN
IF ((UPDATE(data)))
BEGIN
SET NOCOUNT ON;
DECLARE #date bigint
SET #date = datepart(yyyy,getdate())*10000000000+datepart(mm,getdate())*100000000+datepart(dd,getdate())*1000000+datepart(hh,getdate())*10000+datepart(mi,getdate())*100+datepart(ss,getdate())
INSERT INTO historicProductCustomFields (productId,customFieldNumber,data,effectiveDate) (SELECT productId,customFieldNumber,data,#date from inserted)
END
END
Schema:
CREATE TABLE [dbo].[productCustomFields](
[id] [int] IDENTITY(1,1) NOT NULL,
[productId] [int] NOT NULL,
[customFieldNumber] [int] NOT NULL,
[data] [varchar](50) NULL,
CONSTRAINT [PK_productCustomFields] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[historicProductCustomFields](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[productId] [int] NOT NULL,
[customFieldNumber] [int] NOT NULL,
[data] [varchar](50) NULL,
[effectiveDate] [bigint] NOT NULL,
CONSTRAINT [PK_historicProductCustomFields] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
I insert and update only on one record at a time on the productCustomFields table. It seems to work 99% of the time and hard to test for failure. Can anyone shed some light on what I may be doing wrong or better practices for this type of trigger?
Environment is Sql Server Express 2005. I haven't rolled out the service pack yet for sql server either for this particular client.

I think the right way to solve this is keep a TRY CATCH block when inserting into the dbo.historicProductCustomFields table and write the errors into a custom errorlog table. From there it is easy to track this down.
I also see a PK on the historicProductCustomFields table but if you insert and update a given record in ProductCustomFields table then won't you get primary key violations on the historicProductCustomFields table?

You should schema qualify your table that you are inserting into.
You should check to ensure that there are not multiple triggers on the table, as if there are, only 1 trigger for that type of trigger will fire and if there are 2 defined, they are run in random order. In other words, 2 triggers of the same type (AFTER INSERT) then one would fire and the other would not, but you don't necessary have control as to which will fire.

try to use this trigger. i just give you example try to write trigger with this trigger.
create TRIGGER [dbo].[insert_Assets_Tran]
ON [dbo].[AssetMaster]
AFTER INSERT , UPDATE
AS BEGIN
DECLARE #isnum TINYINT;
SELECT #isnum = COUNT(*) FROM inserted;
IF (#isnum = 1)
INSERT INTO AssetTransaction
select [AssetId],[Brandname],[SrNo],[Modelno],[Processor],[Ram],[Hdd],[Display],[Os],[Office],[Purchasedt]
,[Expirydt],[Vendor],[VendorAMC],[Typename],[LocationName],[Empid],[CreatedBy],[CreatedOn],[ModifiedBy]
,[ModifiedOn],[Remark],[AssetStatus],[Category],[Oylstartdt],[Oylenddt],[Configuration]
,[AStatus],[Tassign]
FROM inserted;
ELSE
RAISERROR('some fields not supplied', 16, 1)
WITH SETERROR;
END

Related

Access Linked Table from SQL Shows #Delete

I created this table:
CREATE TABLE [dbo].[dbo_Country]
(
[Country] [nvarchar](100) NOT NULL,
[ISO3166Code] [smallint] NULL,
[CountryEn] [nvarchar](255) NULL,
[Abriviation] [nvarchar](255) NULL,
CONSTRAINT [dbo_Country$PrimaryKey]
PRIMARY KEY CLUSTERED ([Country] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Then I linked it to a MS Access database I try to open the table and see the information but see this:
Does anyone have a solution?
#Deleted is normally shown when rows have been deleted in the underlaying database table while the table is open in Access. They may have been deleted by you in another window or by other users. #Deleted will not show initially when you open the table in Access. Type Shift-F9 to requery. The deleted rows should disappear.
Set a default of 0 for the number (ISO3166Code)
(update all existing number column to = 0.)
Add a row version column (timestamp - NOT date time).
Re-link your table(s).
This is a long time known issue. With bit fields (or int) as null, then you will get that error. As noted, also add a timestamp column (not a datetime column).

Updateable view of local table and linked server table - data has changed

i need to combine two tables on a local and a linked server in a updateable view on my local sql-server, which i link to an MS Access Frontend.
Accessing this view in Access works, and updates to existing rows on the local table works to. But i can not add new rows to this local table as the foreign key [ProjektNr] is not set automatically. Sadly it is not possible to add a foreign key contraint between local and linked server, so i need an alternative. I already read about replicating/tringgering the foreign table in a local table, but this is not what i want. The two tables have a 1:1 relation. If a want to attach [Notizen] to a known Project, i need a new row in [tblProjekt] with matching [ProjektNr], but this row is not generated by updating the view. I get:
data has changed since the results pane was last retrieved
even directly in SSMS.
my local table where i can attach further projectinformation to existing projects: (SQL-Server 2014)
CREATE TABLE [dbo].[tblProjekt](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ProjektNr] [int] NOT NULL,
[Notizen] [nvarchar](max) NULL,
[TimeStamp] [timestamp] NOT NULL,
CONSTRAINT [PK_tblProjekt] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
my linked server table which i don´t want to touch: (SQL-Server 2008R2)
CREATE TABLE [dbo].[Projekt](
[MandantNr] [smallint] NOT NULL,
[ProjektNr] [int] NOT NULL,
[KundenNr] [int] NULL,
[ProjektName] [nvarchar](150) NULL,
[Abgeschlossen] [bit] NULL,
CONSTRAINT [PK_Projekt] PRIMARY KEY NONCLUSTERED
(
[MandantNr] ASC,
[ProjektNr] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Projekt] WITH NOCHECK ADD CONSTRAINT [FK_Projekt_Mandanten] FOREIGN KEY([MandantNr])
REFERENCES [dbo].[Mandanten] ([MandantNr])
GO
ALTER TABLE [dbo].[Projekt] CHECK CONSTRAINT [FK_Projekt_Mandanten]
GO
my local combining view:
SELECT Projekt_1.ProjektNr, Projekt_1.KundenNr, Projekt_1.ProjektName,
CASE WHEN (tblProjekt.ProjektNr IS NULL) THEN '0' ELSE '-1' END AS Übernommen, dbo.tblProjekt.ID, dbo.tblProjekt.ProjektNr AS GProjektNr, dbo.tblProjekt.Notizen, dbo.tblProjekt.TimeStamp, Projekt_1.Abgeschlossen, Projekt_1.MandantNr
FROM LINKEDSERVER.Catalog.dbo.Projekt AS Projekt_1 LEFT OUTER JOIN dbo.tblProjekt ON Projekt_1.ProjektNr = dbo.tblProjekt.ProjektNr
WHERE (Projekt_1.Abgeschlossen = 0) AND (Projekt_1.MandantNr = 1)
Problem solved:
Sadly SQL-Server seems not to be able to solve this simple task.
I linked the to tables in Access, wrote the same query and it worked instantly.

MS SQL Check for duplicate in two fields

I am trying create a trigger that will check if the Author already exist in a table based on a combination of their first and last name. From what Ive been reading this trigger should work, but when I try to insert any new author into the table it gives the "Author exists in table already!" error even though I am inserting an author that does not exist in the table.
Here is the trigger
USE [WebsiteDB]
GO
CREATE TRIGGER [dbo].[tr_AuthorExists] ON [dbo].[Authors]
AFTER INSERT
AS
if exists ( select * from Authors
inner join inserted i on i.author_fname=Authors.author_fname AND i.author_lname=Authors.author_lname)
begin
rollback
RAISERROR ('Author exists in table already!', 16, 1);
End
Here is the table
CREATE TABLE [dbo].[Authors](
[author_id] [int] IDENTITY(1,1) NOT NULL,
[author_fname] [nvarchar](50) NOT NULL,
[author_lname] [nvarchar](50) NOT NULL,
[author_middle] [nvarchar](50) NULL,
CONSTRAINT [PK_Authors] PRIMARY KEY CLUSTERED
(
[author_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Any assistance would be appreciated!
You will need to do this as an INSTEAD of trigger. This also means you need to actually perform the insert inside the trigger. Something along these lines.
CREATE TRIGGER [dbo].[tr_AuthorExists] ON [dbo].[Authors]
instead of insert
AS
set nocount on;
if exists
(
select * from Authors a
inner join inserted i on i.author_fname = a.author_fname AND i.author_lname = a.author_lname
)
begin
rollback
RAISERROR ('Author exists in table already!', 16, 1);
End
else
insert Authors
select i.author_fname
, i.author_lname
, i.author_middle
from inserted i

Generating a Database from SQL script in Visual Studio

I was recently given a project using ASP.NET, C#, and an SQL database. I am somewhat familiar with ASP.NET and C#, however I have never used the Microsoft database software in visual studio. I simply need to generate a database from an SQL script given to me. I was able to get the database mostly generated, however some of the code (The part adding items to one of the tables) did not run on execution. I have tried adding other scripts and rerunning the first one, I cannot get anything to work. I know the script is fine, I just cant get it to run correctly. Thanks for the help. Here's the script
/*These first few lines don't run */
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Product](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](128) NOT NULL,
CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[ProductNote](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ProductID] [int] NOT NULL,
[NoteText] [nvarchar](1000) NOT NULL,
[CreateDate] [datetime] NOT NULL DEFAULT (GETDATE()),
[Archived] [BIT] NOT NULL DEFAULT (0)
CONSTRAINT [PK_ProductNote] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ProductNote] WITH CHECK ADD CONSTRAINT [FK_ProductNote_Product] FOREIGN KEY([ProductID])
REFERENCES [Product] ([ID])
GO
ALTER TABLE [dbo].[ProductNote] CHECK CONSTRAINT [FK_ProductNote_Product]
GO
/*This part does not run either */
DECLARE #n INT = 1
WHILE (#n <=20)
BEGIN
INSERT INTO dbo.Product (Name) SELECT 'Product ' + CONVERT(VARCHAR(10),#n)
SET #n = #n + 1
END
SET ANSI_PADDING OFF
GO
In Visual Studio
Go to View->Solution Explorer
Then Connect your sql Data Base
following links might be helpfull ro connect your db in visual studio
1.http://support.webecs.com/kb/a204/how-do-i-connect-to-sql-server-using-visual-studio-_net.aspx
2.https://support.zen.co.uk/kb/Knowledgebase/SQL-Server-Connecting-to-your-database-through-code-or-Visual-StudioNET
Expand your DB then Right Click on Stored Procedure -> Add new stored procedure
Replace all text with your script->Select All->Right Click ->Run Selection
That's it.

Change NVARCHAR to VARCHAR column data type

When trying to change column from NVARCHAR(max) to VARCHAR(max) I'm getting error:
Cannot create a row of size 8063 which is greater than the allowable maximum row size of 8060.
This is correct because of different storage needed to store unicode characters. But is there any way to force SQL Server to make this conversion?
EDIT: Table definition and alter command:
CREATE TABLE [Descriptions](
[SerialNo] [varchar](20) NOT NULL,
[LanguageCode] [char](2) NOT NULL,
[Note] [nvarchar](max) NOT NULL,
[Address] [varchar](2000) NOT NULL,
[StoreId] [varchar](3) NULL,
CONSTRAINT [UK_Descriptions] UNIQUE NONCLUSTERED
(
[SerialNo] ASC,
[LanguageCode] ASC,
[StoreId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
-- Alter column:
ALTER TABLE [Descriptions] ALTER COLUMN [Note] varchar(max) NOT null;
Try to empty your table first then do the change because it seems that a row store the existing data which over its limit. Take your data out, do your change then re-insert the data.
DECLARE #H nvarchar(max) = N'ESŐNAP' -- rainy day in Hungarian
SELECT CONVERT(varchar(max),#H)
result:
ESONAP

Resources