Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use text, ntext, or image columns in the 'inserted' and 'deleted' tables

Cannot use text, ntext, or image columns in the 'inserted' and 'deleted' tables.

What should be the workaround in this case? :(

like image 282
DucDigital Avatar asked Dec 20 '09 12:12

DucDigital


People also ask

What is the usage of inserted and deleted tables in the database trigger?

In DML triggers, the inserted and deleted tables are primarily used to perform the following: Extend referential integrity between tables. Insert or update data in base tables underlying a view. Test for errors and take action based on the error.

What are inserted and deleted table?

An inserted table is a pseudo-table containing rows with the inserted values of an insert statement, and a deleted table is a pseudo-table containing rows with the updated values (after image) of an update statement.

What is the purpose of the inserted and deleted tables in SQL Server?

Inserted and deleted are the magic tables in the SQL Server trigger that used to manage pre-updated and post updated row.

How can you capture the length of a column when it is a text Ntext and or image data type?

Solution. In addition to the LEN() function, SQL Server also has a DATALENGTH() function. This function can be used on all data types in your table. That's all there is to it.


2 Answers

As of SQL Server 2005, TEXT/NTEXT/IMAGE are deprecated - you should use the (N)VARCHAR(MAX) and VARBINARY(MAX) data types instead.

(N)VARCHAR(MAX) (see MSDN docs here) and VARBINARY(MAX) allow up to 2 GByte of data

From the MSDN docs:

nvarchar [ ( n | max ) ]

Variable-length Unicode character data. n can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes. (= 2 GB)

The (N)VARCHAR(MAX) types also allow all the usual T-SQL string function to work on them - something that wasn't the case with (N)TEXT at all.

As this MSDN article shows, the replacement types are supported in triggers, too:

SQL Server 2008 does not allow for text, ntext, or image column references in the inserted and deleted tables for AFTER triggers. However, these data types are included for backward compatibility purposes only. The preferred storage for large data is to use the varchar(max), nvarchar(max), and varbinary(max) data types. Both AFTER and INSTEAD OF triggers support varchar(max), nvarchar(max), and varbinary(max) data in the inserted and deleted tables.

like image 185
marc_s Avatar answered Oct 12 '22 22:10

marc_s


This is the workaround:

SQL Trigger cannot do INSTEAD OF DELETE but is required for ntext, image columns

Essentially you need to join the inserted and/or deleted pseudo-tables onto the underlying table and read the NTEXT, TEXT or IMAGE data from the underlying tables.

like image 21
Ben Avatar answered Oct 13 '22 00:10

Ben