将文本与varchar(max)参数进行比较,得出字符串或二进制数据将被截断

时间:2019-01-17 10:25:12

标签: sql-server tsql

我可以将超过8k的文本插入到TEXT列中,但是由于某些原因,我无法使用完全相同的数据来执行LIKE。有人可以解释我在做什么错吗?

BEGIN TRAN

CREATE TABLE #log (
    body [text] NULL
 )
GO

DECLARE @longString varchar(max) 
SET @longString = 'Ask Question
I am involved in a data migration project. I am getting the following error when I try to insert data from one table into another table (SQL Server 2005):

Msg 8152, Level 16, State 13, Line 1
String or binary data would be truncated.

The source data columns match the data type and are within the length definitions of the destination table columns so I am at a loss as to what could be causing this error.

sql-server tsql sql-server-2005 migration data-migration
shareeditflag
edited Sep 24 ''18 at 15:31

Lukasz Szozda
79.5k1061105
asked Jun 17 ''11 at 16:24

Jim Evans
3,44092954
Would you mind posting some code, and information about each table? – Kevin Mansel Jun 17 ''11 at 16:27
The tables are both quite large - so I will post only the part of the table definintions that are involved and the code - is that acceptable? – Jim Evans Jun 17 ''11 at 16:30
The table definitions and the code would be great. – IAmTimCorey Jun 17 ''11 at 16:31
add a comment
start a bounty
19 Answers
active oldest votes

141

You will need to post the table definitions for the source and destination tables for us to figure out where the issue is but the bottom line is that one of your columns in the source table is bigger than your destination columns. It could be that you are changing formats in a way you were not aware of. The database model you are moving from is important in figuring that out as well.

shareeditflag
edited Sep 4 ''14 at 18:11

Ryan Kohn
7,782104478
answered Jun 17 ''11 at 16:30

IAmTimCorey
13.8k52756
1
Per my comment above - comming shortly :) – Jim Evans Jun 17 ''11 at 16:32
3
I had faced the same problem and had to compare all the column types and sizes of both the tables to fix the issue. – Aziz Shaikh Jun 17 ''11 at 16:40
1
After going thourgh the exeecise of gathering the partial table definitions and then getting my sproc code the offending column jumped out at me like a lightning bolt... Thanks all for your input. – Jim Evans Jun 17 ''11 at 16:47
I can''t tell you how many times I''ve done the same thing. Glad you were able to solve your issue. – IAmTimCorey Jun 17 ''11 at 16:54
I marked you first reply as the answer because it was what led me to find the answer:) – Jim Evans Jun 17 ''11 at 17:25 
add a comment |  show 1 more comment

0

SQL Server 2019 will finally return more meaningful error message.

Binary or string data would be truncated => error message enhancments

if you have that error (in production), it''s not obvious to see which column or row this error comes from, and how to locate it exactly.

To enable new behavior you need to use DBCC TRACEON(460). New error text from sys.messages:

SELECT * FROM sys.messages WHERE message_id = 2628
2628 – String or binary data would be truncated in table ‘%.*ls’, column ‘%.*ls’. Truncated value: ‘%.*ls’.

String or Binary data would be truncated: replacing the infamous error 8152

This new message is also backported to SQL Server 2017 CU12 (and in an upcoming SQL Server 2016 SP2 CU), but not by default. You need to enable trace flag 460 to replace message ID 8152 with 2628, either at the session or server level.

Note that for now, even in SQL Server 2019 CTP 2.0 the same trace flag 460 needs to be enabled. In a future SQL Server 2019 release, message 2628 will replace message 8152 by default.

SQL Server 2017 CU12 also supports this feature.

Improvement: Optional replacement for "String or binary data would be truncated" message with extended information in SQL Server 2017

This SQL Server 2017 update introduces an optional message that contains the following additional context information.

Msg 2628, Level 16, State 6, Procedure ProcedureName, Line Linenumber
String or binary data would be truncated in table ''%.*ls'', column ''%.*ls''.
Truncated value: ''%.*ls''.
The new message ID is 2628. This message replaces message 8152 in any error output if trace flag 460 is enabled.

db<>fiddle demo

shareeditflag
edited Dec 4 ''18 at 20:20
answered Sep 24 ''18 at 15:29

Lukasz Szozda
79.5k1061105
add a comment

0

I wrote a useful store procedure to help identify and resolve the problem of text truncation (String or binary data would be truncated) when the INSERT SELECT statement is used. It compares fields CHAR, VARCHAR, NCHAR AND NVARCHAR only and returns an evaluation field by field in case of being the possible cause of the error.

EXEC dbo.GetFieldStringTruncate SourceTableName, TargetTableName
This stored procedure is oriented to the problem of text truncation when an INSERT SELECT statement is made.

The operation of this stored procedure depends on the user previously identifying the INSERT statement with the problem. Then inserting the source data into a global temporary table. The SELECT INTO statement is recommended.

You must use the same name of the field of the destination table in the alias of each field of the SELECT statement.

FUNCTION CODE:

DECLARE @strSQL nvarchar(1000)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects where id = OBJECT_ID(N''[dbo].[GetFieldStringTruncate]''))
    BEGIN
        SET @strSQL = ''CREATE PROCEDURE [dbo].[GetFieldStringTruncate] AS RETURN''
        EXEC sys.sp_executesql @strSQL
    END

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
------------------------------------------------------------------------------------------------------------------------
    Description:    
                    Syntax 
                    ---------------
                    dbo.GetFieldStringTruncate(SourceTable, TargetTable)
                    +---------------------------+-----------------------+
                    |   SourceTableName         |   VARCHAR(255)        |
                    +---------------------------+-----------------------+
                    |   TargetTableName         |   VARCHAR(255)        |
                    +---------------------------+-----------------------+

                    Arguments
                    ---------------
                    SourceTableName
                    The name of the source table. It should be a temporary table using double charp ''##''. E.g. ''##temp''

                    TargetTableName
                    The name of the target table. It is the table that receives the data used in the INSERT INTO stament.

                    Return Type
                    ----------------
                    Returns a table with a list of all the fields with the type defined as text and performs an evaluation indicating which field would present the problem of string truncation.

                    Remarks
                    ----------------
                    This stored procedure is oriented to the problem of text truncation when an INSERT SELECT statement is made.
                    The operation of this stored procedure depends on the user previously identifying the INSERT statement with the problem. Then inserting the source data into a global temporary table. The SELECT INTO statement is recommended.
                    You must use the same name of the field of the destination table in the alias of each field of the SELECT statement.

                    Examples
                    ====================================================================================================

                    --A. Test basic

                        IF EXISTS (SELECT * FROM sys.objects  WHERE OBJECT_ID = OBJECT_ID(N''[dbo].[tblDestino]'') AND TYPE IN (N''U''))
                            DROP TABLE tblDestino

                        CREATE TABLE tblDestino
                        (
                            Id INT IDENTITY,
                            Field1 VARCHAR(10),
                            Field2 VARCHAR(12),
                            Field3 VARCHAR(11),
                            Field4 VARCHAR(16),
                            Field5 VARCHAR(5),
                            Field6 VARCHAR(1),
                            Field7 VARCHAR(1),
                            Field8 VARCHAR(6),
                            Field9 VARCHAR(6),
                            Field10 VARCHAR(50),
                            Field11 VARCHAR(50),
                            Field12 VARCHAR(50)
                        )

                        INSERT INTO dbo.tblDestino
                        (
                             Field1 ,
                             Field2 ,
                             Field3 ,
                             Field4 ,
                             Field5 ,
                     '

 PRINT LEN(@longString )

 INSERT INTO #log  ( body) VALUES (@longString )

 SELECT * FROM #log WHERE body LIKE @longString

 DROP TABLE #log

 ROLLBACK TRAN 

1 个答案:

答案 0 :(得分:5)

根据文档:

  

pattern是要在其中搜索的特定字符串   match_expression,并且可以包含以下有效的通配符   字符。模式最多可以包含8,000个字节。

来源https://docs.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql?view=sql-server-2017

因此您不能使用LIKE运算符之后的长度超过8000个字符的字符串,如果这样做会被截断,因此会出现错误。