Trouble using an equal sign in SQL trigger - sql

This is my table:
CREATE TABLE [dbo].[tblVisitors] (
[Id] BIGINT IDENTITY (1, 1) NOT NULL,
[IP] NVARCHAR (100) NOT NULL,
[ProfileId] INT NULL,
[DateVisit] DATE NOT NULL,
[TimeVisit] TIME (0) NOT NULL,
[Browser] NVARCHAR (50) NOT NULL,
[UserOS] NVARCHAR (500) NOT NULL,
CONSTRAINT [PK_tblVisitors] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_tblVisitors_tblProfile] FOREIGN KEY ([ProfileId]) REFERENCES [dbo].[tblProfile] ([Id]) ON DELETE SET NULL
);
I wrote a trigger to avoid redundancy:
CREATE TRIGGER [dbo].[Trigger_tblVisitors_OnInsert]
ON [dbo].[tblVisitors]
INSTEAD OF INSERT
AS
BEGIN
SET NoCount ON;
DECLARE #C INT;
SELECT *
INTO #TEMP
FROM inserted A
WHERE
NOT EXISTS (SELECT *
FROM tblVisitors B
WHERE (A.IP = B.IP)
AND (A.DateVisit = B.DateVisit)
AND (A.ProfileId = B.ProfileId));
IF (SELECT COUNT(*) FROM #TEMP) = 0
BEGIN
PRINT 'DUPLICATE RECORD DETECTED';
ROLLBACK TRANSACTION;
RETURN;
END
INSERT INTO tblVisitors (IP, ProfileId, DateVisit, TimeVisit, Browser, UserOS)
SELECT IP, ProfileId, DateVisit, TimeVisit, Browser, UserOS
FROM #TEMP;
END
But as this part of the code does not work, redundancy occurs:
(A.ProfileId = B.ProfileId)
Because after deleting this section, the operation is performed correctly. But this condition must be checked.

Using my psychic skills, I suspect that you have ProfileId values that are null, and in SQL the expression null = null is not true, but your logic requires it to be true.
Try this:
AND (A.ProfileId = B.ProfileId OR (A.ProfileId IS NULL AND B.ProfileId IS NULL))

Related

How to insert data in multiple tables using single query in SQL Server?

I'm trying to insert data into multiple tables if it doesn't already exist. I can't seem to figure this out at all.
Table 1:
CREATE TABLE [dbo].[search_results]
(
[company_id] [int] NULL,
[title] [text] NULL,
[link] [text] NULL,
[domain] [text] NULL,
[index] [int] NULL,
[id] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL
)
Table 2:
CREATE TABLE [dbo].[statements]
(
[statement_link_id] [int] NULL,
[statement_page] [text] NULL,
[statement_text_location] [text] NULL,
[statement_description] [text] NULL,
[statement_description_html] [text] NULL,
[statement] [int] NULL,
[id] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL
)
This is what I want to do:
check to see if the company_id and the link already exist in the table or not.
SELECT *
FROM search_results
WHERE company_id = 4 AND link = 'https://test.com';
If the data does not exist, insert it into two tables
INSERT INTO search_results (company_id, link, title, domain)
VALUES (4, 'https://test.com', 'title', 'test.com');
and also insert the search_result last inserted id to the following table. corporate_statement value is always 1
INSERT INTO corporate_statements (statement_link_id, corporate_statement)
VALUES (743, 1);
I'm trying this based on what I found on SO
DECLARE #result AS TABLE (id int, company_id int, link text, title text, domain text);
WITH cte AS
(
SELECT *
FROM (VALUES (4, 'https://test.com', null, null)) AS t(company_id, link, title, domain)
)
INSERT INTO #result
SELECT *
FROM
(INSERT INTO dbo.search_results (company_id, link, title, domain)
OUTPUT inserted.*
SELECT * FROM cte
WHERE NOT EXISTS (SELECT * FROM dbo.[search_results]
WHERE company_id = cte.company_id
AND CAST(link AS varchar(250)) = CAST(cte.link AS varchar(50))
)) r
SELECT * FROM #result;
Even trying with a single insert statement, I get the following error:
Msg 213, Level 16, State 1, Line 8
Column name or number of supplied values does not match table definition.
As you can see, I also tried to cast it to varchar since it was throwing error when I hadn't. How can update this?
To me - this seems a lot cleaner, and it also will be a lot simpler to understand (and maintain!) in the future:
-- check to see if your data already exists
IF NOT EXISTS (SELECT *
FROM search_results
WHERE company_id = 4 AND link = 'https://test.com')
BEGIN TRY
BEGIN TRANSACTION
-- if not -> insert into the first table
INSERT INTO search_results (company_id, link, title, domain)
VALUES (4, 'https://test.com', 'title', 'test.com');
-- grab the last identity value from that previous INSERT
DECLARE #LastId INT;
SELECT #LastId = SCOPE_IDENTITY();
-- insert into the second table
INSERT INTO corporate_statements (statement_link_id, corporate_statement)
VALUES (#LastId, 1);
COMMIT;
END TRY
BEGIN CATCH
-- in case of an error rollback the full transaction
ROLLBACK;
END CATCH;
and you're done. Or am I missing something? I think this would be doing what you're described in the intro of your post - not necessarily what you're showing in your code...

SQL Server (SSMS) Losing or Not Recognizing Transaction

I've run into an issue a couple times now where I'll encase a query in BEGIN TRAN / ROLLBACK TRAN (so I can verify it works before committing any changes), and will get the error below. The BEGIN TRAN statement does not generate an error.
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION
The commands I was using the most recent time are below. I didn't save the errors at the time, but I believe that the UPDATE commands also errored because it didn't recognize ClientId as a valid column.
Each time it has done this, some statements have been rolled back, and others remained. In this case, I have neither a ClientId nor a ClientCode column.
I also can't perfectly recreate the initial run since running these outside of a transaction has caused me to lose all of my ClientCode fields, and the ClientId fields are not in the tables. Thankfully, none of the dev data was important, but because of its volume, it'll take me a little bit to repopulate.
Initially, I thought I'd just selected some of the query before running it, ommiting the BEGIN TRAN, so I reran it, careful to select everything and got the same error, as well as a host of others caused by the missing ClientCode field.
I'd like to know why this is happening so I can prevent it in the future.
EDIT: I did some additional testing on a later date and I have been unable to recreate this behavior. The transactions are being rolled back correctly, and the UPDATE command is not erroring for having an invalid column
BEGIN TRAN
ALTER TABLE tblInvoices ADD ClientId INT NULL
GO
UPDATE tblInvoices
SET ClientId = c.Id
FROM tblInvoices i
INNER JOIN Core.dbo.tblClients c
ON i.ClientCode = c.ClientCode
GO
ALTER TABLE tblInvoices ALTER COLUMN ClientId INT NOT NULL
GO
ALTER TABLE tblInvoices DROP COLUMN ClientCode
GO
ALTER TABLE tblClientSettings ADD ClientId INT NULL
GO
UPDATE tblClientSettings
SET ClientId = c.Id
FROM tblClientSettings cs
INNER JOIN Core.dbo.tblClients c
ON cs.ClientCode = c.ClientCode
GO
ALTER TABLE tblClientSettings ALTER COLUMN ClientId INT NOT NULL
GO
ALTER TABLE tblClientSettings DROP COLUMN ClientCode
GO
ROLLBACK TRAN
EDIT 2: It happened again on a small set of commands. The commands and the output messages are below.
Input:
BEGIN TRAN
CREATE TABLE tblEmailTemplates(
Id INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
Subject NVARCHAR(2000) NULL,
Body NVARCHAR(MAX) NULL,
Sender NVARCHAR(200) NULL,
Recipients NVARCHAR(2000) NULL,
CC NVARCHAR(2000) NULL,
BCC NVARCHAR(2000) NULL,
Html BIT NULL
)
CREATE TABLE tblContactSeries (
Id INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
AppId INT NOT NULL REFERENCES Foo_Apps.dbo.tblApps(Id),
Description NVARCHAR(200) NOT NULL
)
CREATE TABLE [dbo].tblEmails(
[Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
SeriesId INT NOT NULL REFERENCES tblContactSeries(Id),
TemplateId INT NULL REFERENCES tblEmailTemplates(Id),
TemplateParameters NVARCHAR(MAX) NULL,
[Sender] [nvarchar](200) NULL,
[Recipients] [nvarchar](2000) NULL,
[CC] [nvarchar](2000) NULL,
[BCC] [nvarchar](2000) NULL,
[Subject] [nvarchar](2000) NULL,
[Body] [nvarchar](max) NULL,
[Html] [bit] NOT NULL,
[ScheduledDate] [datetime] NOT NULL,
[OverdueDate] [datetime] NULL,
[Active] [bit] NOT NULL,
[Sent] [bit] NOT NULL,
[SendTime] [datetime] NULL,
[SendSuccess] [bit] NULL
)
CREATE TABLE [dbo].[tblAttachments](
[Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
EmailId [int] NOT NULL REFERENCES tblEmails(Id),
[FilePath] [nvarchar](2000) NULL,
[FileName] [nvarchar](200) NULL
)
GO
CREATE VIEW vwPendingAttachments AS
SELECT a.*
FROM tblAttachments a
INNER JOIN tblEmails e
ON a.EmailId = e.Id
WHERE e.Active = 1 AND e.Sent != 1
GO
ROLLBACK TRAN
Messages:
Msg 1763, Level 16, State 0, Line 23
Cross-database foreign key references are not supported. Foreign key 'Foo_Apps.dbo.tblApps'.
Msg 1750, Level 16, State 1, Line 23
Could not create constraint or index. See previous errors.
Msg 208, Level 16, State 1, Procedure vwPendingAttachments, Line 4 [Batch Start Line 59]
Invalid object name 'tblAttachments'.
Msg 3903, Level 16, State 1, Line 70
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.

SQL Trigger throws error but still inserts

I am working on a trigger that is supposed to block an insert when #verkoperstatus is 0; this does function, but for some reason it also stops the insert when #verkoperstatus is 1. What could be the root cause behind this?
CREATE TRIGGER [dbo].[verkoper_check] ON [dbo].[Verkoper]
FOR INSERT,UPDATE
AS
BEGIN
DECLARE #verkoperstatus bit
DECLARE #gebruikersnaam varchar(25)
SELECT #gebruikersnaam = gebruikersnaam FROM inserted
SELECT #verkoperstatus = verkoper FROM Gebruiker WHERE gebruikersnaam = #gebruikersnaam
IF #verkoperstatus = 0
BEGIN
RAISERROR('Geen verkoper!',18,1);
ROLLBACK;
END
ELSE
BEGIN
COMMIT;
END
END
It should insert when #verkoperstatus is 1, and raise an error when #verkopstatus is 0.
The table Gebruiker is references, which includes a 'gebruikersnaam' and a 'verkoper' column. The value of the 'gebruikersnaam' column is the identifying column which (in this specific case is 'Lars'). Verkoper is a bit column, which indicated if one is a seller or not, so this has the value of a 0 or a 1.
The goal I am trying to achieve is to have an insert on the Verkoper tabel if a 'gebruikersnaam' has the 'verkoper' value of one.
This means if there is a row in Gebruiker with the 'gebruikersnaam' of Lars and the verkoper has a value of 1. This will be an allowed insert into the Verkoper tabel.
As the Verkoper has the following columns: 'gebruikersnaam', 'banknaam', 'rekeningnummer', 'controleoptienaam' and 'creditcardnummer'. When 'gebruikersnaam' corresponds with a 'gebruikersnaam' from the Gebruikers table AND has a value of 1 in the 'verkoper' column this record will be allowed to be inserted into the Verkoper table.
As of now there is a row in the Gebruikers column which includes the gebruikersnaam 'Lars' and a verkoper value of '1'. Meaning any SQL Insert with the gebruikersnaam of 'Lars' should be allowed into the Verkoper table.
This however does not function the way I believe it should.
These are the tables mentioned above:
CREATE TABLE Verkoper (
gebruikersnaam varchar(25) NOT NULL,
banknaam varchar(255) NULL,
rekeningnummer varchar(32) NULL,
controleoptienaam char(10) NOT NULL,
creditcardnummer integer NULL,
CONSTRAINT pk_Verkoper PRIMARY KEY (gebruikersnaam),
CONSTRAINT fk_Verkoper_Gebruikersnaam FOREIGN KEY (gebruikersnaam) REFERENCES Gebruiker(gebruikersnaam),
CONSTRAINT ck_rekening CHECK (rekeningnummer is NOT NULL OR creditcardnummer is NOT NULL),
CONSTRAINT ck_controleoptie CHECK (controleoptienaam IN('Post', 'Creditcard'))
)
CREATE TABLE Gebruiker(
gebruikersnaam varchar(25) NOT NULL,
voornaam varchar(25) NOT NULL,
achternaam varchar(25) NOT NULL,
adresregel_1 varchar(255) NULL,
adresregel_2 varchar(255) NULL,
postcode char(7) NULL,
plaatsnaam varchar(255) NULL,
land varchar(255) NULL,
geboortedag char(10) NOT NULL,
mailbox varchar(255) NOT NULL,
wachtwoord varchar(255) NOT NULL,
verkoper bit NOT NULL,
CONSTRAINT pk_gebruiker PRIMARY KEY (gebruikersnaam),
)
For the inserts I am using the following data:
INSERT INTO Gebruiker VALUES ('Lars', 'Lars', 'Last_name', null, null, null, null, null, '04/04/2019', 'lars#mymailbox.cloud', 'MyPassword', 1)
INSERT INTO Verkoper VALUES ('Lars', 'ING', 'NL32ABN32492809', 'Post', null)
This is untested, however, I suspect this is the logic you really need:
CREATE TRIGGER [dbo].[verkoper_check] ON [dbo].[Verkoper]
FOR INSERT,UPDATE
AS BEGIN
IF EXISTS(SELECT 1
FROM inserted i
JOIN Gebruiker G ON i.gebruikersnaam = G.gebruikersnaam
WHERE G.verkoper = 0) BEGIN
RAISERROR('Geen verkoper!',18,1);
ROLLBACK;
END;
END;

How to save auto generated primary key Id in foreign key column in same table

Following is the table structure:
CREATE TABLE [User] (
[Id] bigint identity(1,1) not null,
[FirstName] nvarchar(100) not null,
[LastName] nvarchar(100) not null,
[Title] nvarchar(5) null,
[UserName] nvarchar(100) not null,
[Password] nvarchar(100) not null,
[Inactive] bit null,
[Created] Datetime not null,
[Creator] bigint not null,
[Modified] DateTime null,
[Modifier] bigint null
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[Id] Asc
)
);
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[FK_User_Creator]') AND parent_object_id = OBJECT_ID(N'[User]'))
ALTER TABLE [User] ADD CONSTRAINT [FK_User_Creator] FOREIGN KEY([Creator]) REFERENCES [User]([Id])
GO
INSERT INTO [User] (Creator) Values ([Id] ?)
This is a case when table is empty and first user is going to add in table. Otherwise I don't have issue.
How can I insert Id in creator column with insert statement at the same time?
One way could be using Sequence instead of identity column. The below script might serve the same purpose:
CREATE SEQUENCE dbo.useridsequence
AS int
START WITH 1
INCREMENT BY 1 ;
GO
CREATE TABLE [User] (
[Id] bigint DEFAULT (NEXT VALUE FOR dbo.useridsequence) ,
[FirstName] nvarchar(100) not null,
[LastName] nvarchar(100) not null,
[Title] nvarchar(5) null,
[UserName] nvarchar(100) not null,
[Password] nvarchar(100) not null,
[Inactive] bit null,
[Created] Datetime not null,
[Creator] bigint DEFAULT NEXT VALUE FOR dbo.useridsequence ,
[Modified] DateTime null,
[Modifier] bigint null
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[Id] Asc
)
);
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[FK_User_Creator]') AND parent_object_id = OBJECT_ID(N'[User]'))
ALTER TABLE [User] ADD CONSTRAINT [FK_User_Creator] FOREIGN KEY([Creator]) REFERENCES [User]([Id])
GO
INSERT INTO [User]
(
-- Id -- this column value is auto-generated
FirstName,
LastName,
Title,
UserName,
[Password],
Inactive,
Created,
Creator,
Modified,
Modifier
)
VALUES
(
'Foo',
'Bar',
'Title',
'UserName ',
'Password',
0,
GETDATE(),
DEFAULT,
GETDATE(),
1
)
SELECT * FROM [User] AS u
Result :
The short answer is that you can't do this. And I suggest your model is logically flawed in the first place. Do you intend to define all actual database users (e.g., create user ... for login ...) as rows in [Users]? You need to think about that - but the typical answer is no. If the answer is yes, then you don't need the creator column at all because it is redundant. All you need is the created date - for which you probably should have defined a default.
But if you want to do this, you will need to do it in two steps (and you will need to make the column nullable). You insert a row (or rows) with values for the "real" data columns. Then update those same rows with the identity values generated for id. An example showing different ways to do this
use tempdb;
set nocount on;
CREATE TABLE dbo.[user] (
[user_id] smallint identity(3,10) not null primary key,
[name] nvarchar(20) not null,
[active] bit not null default (1),
[created] Datetime not null default (current_timestamp),
[creator] smallint null
);
ALTER TABLE dbo.[user] ADD CONSTRAINT [fk_user] FOREIGN KEY(creator) REFERENCES dbo.[user](user_id);
GO
-- add first row
insert dbo.[user] (name) values ('test');
update dbo.[user] set creator = SCOPE_IDENTITY() where user_id = SCOPE_IDENTITY()
-- add two more rows
declare #ids table (user_id smallint not null);
insert dbo.[user] (name) output inserted.user_id into #ids
values ('nerk'), ('pom');
update t1 set creator = t1.user_id
from #ids as newrows inner join dbo.[user] as t1 on newrows.user_id = t1.user_id;
select * from dbo.[user] order by user_id;
-- mess things up a bit
delete dbo.[user] where name = 'pom';
-- create an error, consume an identity value
insert dbo.[user](name) values (null);
-- add 2 morerows
delete #ids;
insert dbo.[user] (name) output inserted.user_id into #ids
values ('nerk'), ('pom');
update t1 set creator = t1.user_id
from #ids as newrows inner join dbo.[user] as t1 on newrows.user_id = t1.user_id;
select * from dbo.[user] order by user_id;
drop table dbo.[user];
And I changed the identity specification to demonstrate something few developers realize. It isn't always defined as (1,1) and the next inserted value can jump for many reasons - errors and caching/restarts for example. Lastly, I think you will regret naming a table with a reserved word since references to it will require the use of delimiters. Reduce the pain.

Inserted clause returns 0 when used with triggers

I'm trying to get the last inserted rows Id from an inserts statement on the following table using SQL server 2012
[dbo].[Table](
[TableId] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[CreatedBy] [nvarchar](50) NULL,
[CreatedDate] [datetime2](7) NOT NULL,
[ModifiedBy] [nvarchar](50) NULL,
[ModifiedDate] [datetime2](7) NULL,
CONSTRAINT [pk_Table] PRIMARY KEY CLUSTERED
(
[TableId] ASC
)
I'm also using an audit triggers on that table that are as follows:
trigger [dbo].[trigger_Table_auditColumnAutoInsert]
on [dbo].[Table]
instead of insert
/**************************************************************
* INSTEAD OF trigger on table [dbo].[Table] responsible
for automatically inserting audit column data
**************************************************************/
as
begin
set nocount on
declare #currentTime datetime2
set #currentTime = GETUTCDATE()
insert into [dbo].[Table]
(
Name,
CreatedBy,
CreatedDate,
ModifiedBy,
ModifiedDate
)
select
Name,
ISNULL(CreatedBy, system_user),
#currentTime,
NULL,
NULL
from inserted
select SCOPE_IDENTITY() as [TableId]
goto EOP -- end of procedure
ErrorHandler:
if (##trancount <> 0) rollback tran
EOP:
end
I used different approaches, but nothing 'SAFE' seems to work.
Using scope identity returns null
insert into dbo.[Table](Name) Values('foo')
select SCOPE_IDENTITY()
Using OUTPUT INSERTED always returns 0 for the identity coloumns; although it returns the other inserted values:
declare #tmpTable table
(
TableId int,
Name nvarchar (50)
)
INSERT INTO [dbo].[Table]([Name])
output inserted.TableId, inserted.Name into #tmpTable
VALUES('foo')
select * from #tmpTable
TableId Name
0 foo
I know of another solution to get the inserted Id from the triggers itself, by executing a dynamic sql command as follows:
declare #tmpTable table (id int)
insert #tmpTable (id )
exec sp_executesql N'insert into dbo.[Table](Name) Values(''foo'')'
select id from #tmpTable
I couldn't figure out why in the first 2 cases it is not working; why the SCOPE_IDENTITY() does not work although the triggers execute in the same transaction? And also why the INSERTED clause returns 0 for the identity column.
It appears that the following requirements apply to your audit column data:
Use the insert value supplied for CreatedBy, or use SYSTEM_USER by default.
Always use GETUTCDATE() for CreatedDate.
If the INSTEAD OF trigger (rather than an AFTER trigger) is not essential to your requirements, then you can use DEFAULT constraints on your audit columns and an AFTER INSERT trigger to enforce requirement #2.
CREATE TABLE [dbo].[Table]
(
[TableId] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[CreatedBy] [nvarchar](50) NOT NULL CONSTRAINT [DF_Table_CreatedBy] DEFAULT SYSTEM_USER,
[CreatedDate] [datetime2](7) NOT NULL CONSTRAINT [DF_Table_CreatedDate] DEFAULT GETUTCDATE(),
[ModifiedBy] [nvarchar](50) NULL,
[ModifiedDate] [datetime2](7) NULL,
CONSTRAINT [pk_Table] PRIMARY KEY CLUSTERED ([TableId] ASC)
)
GO
CREATE TRIGGER Trigger_Table_AfterInsert ON [dbo].[Table]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
UPDATE [dbo].[Table] SET [CreatedDate]=GETUTCDATE()
FROM [dbo].[Table] AS T
INNER JOIN INSERTED AS I ON I.[TableId]=T.[TableId]
END
GO
Then, both SCOPE_IDENTITY() and OUTPUT INSERTED techniques to get the new TableId value work as expected.
If the INSTEAD OF trigger is essential to your implementation, then SELECT ##IDENTITY is an alternative to SCOPE_IDENTITY.