I have the table which consist of column with datatype text
.
Table EmployeeMaster
CREATE TABLE [EmployeeMaster]
(
EmpID int identity(1,1),
EmpName varchar(20),
EmpPhone int,
EmpAddress TEXT
);
And I want to create audit log on this table.
Audit Table : EmployeeMaster_Audit
CREATE TABLE [EmployeeMaster_Audit]
(
EmpID int,
EmpName varchar(20),
EmpPhone int,
EmpAddress VARCHAR(MAX)
);
Writing trigger for INSERT.
Trigger :
CREATE TRIGGER [dbo].[EmployeeMaster_Insert]
ON [dbo].[EmployeeMaster]
FOR INSERT
AS
INSERT INTO [dbo].[EmployeeMaster_Audit]
([EmpID], [EmpName], [EmpPhone], [EmpAddress])
SELECT CONVERT(int,[EmpID]) as [EmpID],[EmpName],[EmpPhone],CONVERT(varchar(max),[EmpAddress]) AS [EmpAddress] FROM INSERTED
GO
Error Details : While creating trigger getting following error:
Cannot use text, ntext, or image columns in the 'inserted' and 'deleted' tables.
My Try : CONVERT(varchar(max),[EmpAddress])
Since the trigger is fired after the insert, you can simply query back to the EmployeeMaster
to get the inserted data. Something like this:
CREATE TRIGGER [dbo].[EmployeeMaster_Insert]
ON [dbo].[EmployeeMaster]
FOR INSERT
AS
INSERT INTO [dbo].[EmployeeMaster_Audit] ([EmpID], [EmpName], [EmpPhone], [EmpAddress])
SELECT EM.[EmpID]
, EM.[EmpName]
, EM.[EmpPhone]
, CONVERT(varchar(max), EM.[EmpAddress]) AS [EmpAddress]
FROM INSERTED I
INNER JOIN dbo.[EmployeeMaster] EM
ON EM.[EmpID] = I.[EmpID]
GO
This is assuming you cannot change the text
datatype, see Zohar's answer.
The correct solution to the problem would be to replace the text
column with a varchar(max)
column.
The Image
, Text
, and nText
data types are deprecated since 2008 version introduced varbinary(max)
, varchar(max)
and nvarchar(max)
.
For more information, read Microsoft official documentation page on ntext, text, and image (Transact-SQL) :
IMPORTANT! ntext , text , and image data types will be removed in a future version of SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max) , varchar(max) , and varbinary(max) instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.