Published on

August 8, 2012

Understanding SET TEXTSIZE in SQL Server

Have you ever wondered about the difference between the LEFT function and SET TEXTSIZE in SQL Server? Although this may be an old topic, it is still worth exploring. In this article, we will delve into how TEXTSIZE works and compare it to the LEFT function.

Let’s start by looking at a simple example. Consider a table called MyTable with two columns: ID (INT) and MyText (VARCHAR(MAX)). We will insert a row into this table with a long string of characters.

USE TempDB
GO

-- Create TestTable
CREATE TABLE MyTable (ID INT, MyText VARCHAR(MAX))
GO

INSERT MyTable (ID, MyText)
VALUES(1, REPLICATE('1234567890', 100))
GO

Now, let’s select the data from MyTable using the LEFT function to retrieve only the first 10 characters of the MyText column:

-- Using Left
SELECT ID, LEFT(MyText, 10) MyText
FROM MyTable
GO

Next, we will explore the SET TEXTSIZE statement. This statement allows us to specify the maximum number of bytes that will be returned for each column in the result set. Let’s set the TEXTSIZE to 10 and select the data from MyTable:

-- Set TextSize
SET TEXTSIZE 10;
SELECT ID, MyText
FROM MyTable;
SET TEXTSIZE 2147483647
GO

As you can see, the result set is limited to 10 characters for each column when TEXTSIZE is set to 10. However, when we set TEXTSIZE back to its default value (2147483647), the entire MyText column is returned.

So, what is the difference between the LEFT function and SET TEXTSIZE? The main distinction lies in their usage and scope. The LEFT function is applied only to the column in a single SELECT statement where it is used. On the other hand, SET TEXTSIZE applies to all columns in the SELECT statement and any subsequent SELECT statements until the TEXTSIZE is modified again in the session.

When should you use SET TEXTSIZE? If you are working with SSMS for testing or any non-production related tasks, and you need to retrieve data from a large table with multiple columns containing varchar data, you can consider using SET TEXTSIZE to limit the amount of data retrieved in the result set. However, it’s important to note that this behavior is specific to SSMS and may differ on the server side.

In conclusion, the LEFT function and SET TEXTSIZE are not directly comparable. While they may produce the same result in SSMS, their usage and scope differ significantly. The LEFT function is suitable for single column selection, whereas SET TEXTSIZE affects all columns in the SELECT statement and subsequent SELECT statements until modified again.

We hope this article has provided you with a better understanding of SET TEXTSIZE in SQL Server. We would love to hear your thoughts and experiences with this feature. Please leave a comment below.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.