SQL Server 2008 R2: Trigger on `TEXT` column

本秂侑毒 提交于 2019-12-08 02:43:20

问题


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])


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/49146728/sql-server-2008-r2-trigger-on-text-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!