Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trigger not firing for instead of insert sql server

I am trying to create a trigger to convert a value from varchar to varbinary.
The creation of the trigger is successful. However it is not firing against an insert query.

CODE FOR TRIGGER

USE VacationManager;
GO

CREATE TRIGGER HashPassword
ON Users
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Users(Username,[Password],FirstName,LastName,RoleID)
SELECT
i.Username,
 CONVERT(varbinary(max),EncryptByPassPhrase('iskam_6_za_bazata_moje_i_za_springa',i.[Password]),2) ,
i.FirstName,
i.LastName,
i.RoleID
FROM inserted AS i
END

USERS TABLE

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

USE [VacationManager]
GO

/****** Object:  Table [dbo].[Users]    Script Date: 11/20/2022 8:58:16 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Users](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Username] [varchar](255) NOT NULL,
    [Password] [varbinary](max) NOT NULL,
    [FirstName] [nvarchar](255) NOT NULL,
    [LastName] [nvarchar](255) NOT NULL,
    [RoleID] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[Users]  WITH CHECK ADD  CONSTRAINT [FK_Users.RoleID] FOREIGN KEY([RoleID])
REFERENCES [dbo].[Roles] ([Id])
GO

ALTER TABLE [dbo].[Users] CHECK CONSTRAINT [FK_Users.RoleID]
GO

I tried executing this query:

INSERT INTO Users(Username,[Password],FirstName,LastName,RoleID)
VALUES('martini','parola','martin','atanasov',4)

But the result was:

Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.

>Solution :

You can’t insert a varchar into a varbinary max column. So this

INSERT INTO Users(Username,[Password],FirstName,LastName,RoleID)
VALUES('martini','parola','martin','atanasov',4)

should be

INSERT INTO Users(Username,[Password],FirstName,LastName,RoleID)
VALUES('martini', cast(N'parola' as varbinary(max)),'martin','atanasov',4)

Or you create a view on Users that performs the varbinary>nvarchar cast and put your instead of trigger on that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading