In this article, we’ll take a look into SQL truncate improvement in SQL Server 2019.

在本文中,我们将研究SQL Server 2019中SQL截断改进。

Data inserts and updates are a normal and regular task for the developers and database administrators as well as from the application. The source of the data can be in multiple forms as if direct insert using T-SQL, stored procedures, functions, data import from flat files, SSIS packages etc.

对于开发人员和数据库管理员以及应用程序而言,数据插入和更新是一项正常且常规的任务。 数据源可以采用多种形式,就像使用T-SQL直接插入,存储过程,函数,从平面文件导入数据,SSIS包等。

Sometimes we receive the bad data in terms of character limits more than the defined limit in a column. For example, if we want to insert bulk data into a database table using an insert statement, we get a bad data on character length 11 into employee name column while our existing column (Employee_name) allows only 10 characters, so how SQL Server will behave? it will raise an SQL truncate error. Insert statement will fail in this case. We normally call it as silent truncation and occur when we try to insert string data (varchar, nvarchar, char, nchar) into more than the size of the column.

有时我们收到的不良数据的字符限制要比一列中定义的限制更多。 例如,如果我们想使用插入语句将批量数据插入数据库表,则会在雇员名称列中获得字符长度11的错误数据,而我们现有的列(Employee_name)仅允许10个字符,因此SQL Server的行为? 它将引发SQL截断错误。 在这种情况下,插入语句将失败。 通常,我们将其称为静默截断,并且在我们尝试将字符串数据(varchar,nvarchar,char,nchar)插入超过列大小的情况时发生。

If we are dealing with the huge amount of data with lots of columns, if we get any error it becomes difficult to find out which column, data caused the issue. However, it is important for us to dig out into the data and identify the bad data, fix it in order to import the data. We can use a profiler or extended events to troubleshoot the data insert, update, but again it is a resource and time-consuming. We can also use the custom stored procedure to check the length of the data before inserting into the table, but it is an extra overhead for us. Moreover, if we are getting frequent SQL truncate errors, it might be difficult to troubleshoot using a profiler and extended events in that case. This is the issue developers and DBA used to highlight in a different forum to improve the error related with silent truncation of data so that it can be quickly fixed.

如果我们要处理的数据量很大且包含许多列,那么如果遇到任何错误,则很难找出导致问题的数据列。 但是,对我们来说重要的是深入挖掘数据并识别不良数据,进行修复以导入数据。 我们可以使用事件探查器或扩展事件来对数据插入,更新进行故障排除,但这又是一项资源和耗时的工作。 我们还可以使用自定义存储过程在插入表之前检查数据的长度,但这对我们来说是额外的开销。 此外,如果我们经常遇到SQL截断错误,则在这种情况下使用探查器和扩展事件可能很难进行故障排除。 这是开发人员和DBA经常在另一个论坛中强调的问题,以改善与数据无提示截断有关的错误,以便可以快速修复该错误。

Let us first create a sample database, table and insert some dummy data into it.

让我们首先创建一个示例数据库,表并将一些虚拟数据插入其中。

Create Database SQLShackDemo
Go
Use SQLShackDemo
Go
CREATE TABLE DemoSQL2019
([ID] INT identity(1,1),[NAME] VARCHAR(10),
)
GO

例子1 (Example 1)

INSERT INTO DemoSQL2019 VALUES ('SQLShack ApexSQL Community')
GO
INSERT INTO DemoSQL2019  VALUES ('Rajendra Gupta Author')
GO

As we can see above, we get the SQL truncate error message ‘String or binary data would be truncated.’

如上所示,我们收到了SQL截断错误消息“字符串或二进制数据将被截断”。

Therefore, before we move further, let me explain why this error occurred. In below query, we are checking the length of the string that we want to insert into our workload.

因此,在继续之前,让我解释为什么会发生此错误。 在下面的查询中,我们正在检查要插入到工作负载中的字符串的长度。

select len('SQLShack ApexSQL Community') as [StrringLength]Select len('Rajendra Gupta Author') as [StrringLength]

While using below query, we can check that the Name column in our DemoSQL2019 table allows only 10 characters.

在使用以下查询时,我们可以检查我们的DemoSQL2019表中的Name列仅允许10个字符。

select character_maximum_length,column_name
from information_schema.columns
where table_name = 'DemoSQL2019'
and Column_name='NAME'

As we can see above, SQL truncate error occurred due to the length of the data more than the length of the string allowed in the column.

正如我们在上面看到的,由于数据的长度大于列中允许的字符串的长度,所以发生了SQL截断错误。

例子2 (Example 2)

Let us look at the complex data:

让我们看一下复杂的数据:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customerstest]([CustomerID] [int] NOT NULL,[CustomerName] [nvarchar](30) NOT NULL,[BillToCustomerID] [int] NOT NULL,[CustomerCategoryID] [int] NOT NULL,[BuyingGroupID] [int] NULL,[PrimaryContactPersonID] [int] NOT NULL,[AlternateContactPersonID] [int] NULL,[DeliveryMethodID] [int] NOT NULL,[DeliveryCityID] [int] NOT NULL,[PostalCityID] [int] NOT NULL,[CreditLimit] [decimal](18, 2) NULL,[AccountOpenedDate] [date] NOT NULL,[StandardDiscountPercentage] [decimal](18, 3) NOT NULL,[IsStatementSent] [bit] NOT NULL,[IsOnCreditHold] [bit] NOT NULL,[PaymentDays] [int] NOT NULL,[PhoneNumber] [nvarchar](20) NOT NULL,[FaxNumber] [nvarchar](20) NOT NULL,[DeliveryRun] [nvarchar](5) NULL,[RunPosition] [nvarchar](5) NULL,[WebsiteURL] [nvarchar](256) NOT NULL,[DeliveryAddressLine1] [nvarchar](60) NOT NULL,[DeliveryAddressLine2] [nvarchar](60) NULL,[DeliveryPostalCode] [nvarchar](10) NOT NULL,[DeliveryLocation] [geography] NULL,[PostalAddressLine1] [nvarchar](60) NOT NULL,[PostalAddressLine2] [nvarchar](60) NULL,[PostalPostalCode] [nvarchar](10) NOT NULL,[LastEditedBy] [int] NOT NULL,[ValidFrom] [datetime2](7) NOT NULL,[ValidTo] [datetime2](7) NOT NULL
)
GO

We can notice here that the table involves many columns and we are trying to insert multiple records in our example. Now, we have the same SQL truncate error message, but we did not get any clue about which row is causing the issue. Due to a large number of insert statements, it would be difficult to fix this issue. This is the behavior until SQL Server 2017. Now in below section let us see how SQL Server 2019 solves this issue.

在这里我们可以注意到该表包含许多列,并且我们试图在示例中插入多个记录。 现在,我们有相同SQL截断错误消息,但是我们没有任何有关导致问题的行的线索。 由于有大量的插入语句,因此很难解决此问题。 这是直到SQL Server 2017为止的行为。现在在下面的部分中,让我们看看SQL Server 2019如何解决此问题。

SQL Server 2019的数据截断行为 (SQL Server 2019 behavior for data truncation)

前提条件 (Pre-requisite)

Before we explore the SQL Server 2019 solution to the silent data truncation issue, we should have below pre-requisites:

在探索SQL Server 2019解决静默数据截断问题的解决方案之前,我们应该具有以下先决条件:

  • Installation of SQL Server 2019 Public preview version. 安装SQL Server 2019 Public预览版。
  • SQL Server Management Studio 18.0 Preview 4 SQL Server Management Studio 18.0预览版4

In my previous article, we learned that SQL Server 2019 preview version (SQL Server vNext CTP 2.0) launched recently and you can install it on windows version by following up the SQL Server 2019 overview and installation.

在我的上一篇文章中,我们了解到SQL Server 2019预览版(SQL Server vNext CTP 2.0)最近启动了,您可以通过跟踪SQL Server 2019概述和安装在Windows版本上安装它。

Now let us look at the SQL Server 2019 behavior of this SQL truncate issue. We can see in the database properties, the database compatibility level is set to 150, which is the new compatibility level for SQL Server 2019.

现在让我们看看此SQL截断问题SQL Server 2019行为。 我们可以在数据库属性中看到数据库兼容性级别设置为150,这是SQL Server 2019的新兼容性级别。

If database compatibility level is other than 150, we can change it using the below query.

如果数据库兼容性级别不是150,则可以使用以下查询更改它。

ALTER DATABASE database_name SET COMPATIBILITY_LEVEL = 150

Now let us run the query from the example 1 in this SQL Server 2019 Database with compatibility level 150.

现在让我们在兼容性级别为150的此SQL Server 2019数据库中从示例1运行查询。

We got a similar error ‘String or binary data would be truncated’. So, do we have the same kind of behavior in SQL Server 2019 as well?

我们得到了类似的错误“字符串或二进制数据将被截断”。 因此,我们在SQL Server 2019中是否也具有相同的行为?

No, SQL Server 2019 gives information that is more useful to fix the issue. We get the below message if the string or binary data is truncated.

否,SQL Server 2019提供的信息对于解决此问题更有用。 如果字符串或二进制数据被截断,我们将收到以下消息。

String or binary data would be truncated in table ‘%.*ls’, column ‘%.*ls’. Truncated value: ‘%.*ls’.

字符串或二进制数据将在表'%。* ls'的列'%。* ls'中被截断。 截断的值:'%。* ls'。

This error message highlights clearly the table name, column name, and the truncated value in SQL Server 2019. Therefore, we do not worry or troubleshoot to find the problematic data or column giving this error message. This was a real concern for most of the DBA’s and developers and this feature was in demand from a long time.

此错误消息清楚地突出显示了SQL Server 2019中的表名,列名和截断的值。因此,我们不必担心或进行故障排除,以查找出现此错误消息的有问题的数据或列。 这是大多数DBA和开发人员真正关心的问题,并且很长一段时间以来就一直在需要此功能。

We can look this message into sys. messages table in SQL Server 2019; message id 2628 contains this SQL truncate error message. We can see the table contains error messages for the same error code in the different language. SQL Server picks up the correct message_id based on the collation setting which is the language id in this table.

我们可以将此消息查看sys。 SQL Server 2019中的邮件表; 消息ID 2628包含此SQL截断错误消息。 我们可以看到该表包含不同语言的相同错误代码的错误消息。 SQL Server根据排序规则设置(此表中的语言ID)选择正确的message_id。

While in previous versions till SQL Server 2017, only ‘String or binary data would be truncated’ message is shown

在SQL Server 2017之前的早期版本中,仅显示``字符串或二进制数据将被截断''消息

In SQL Server 2019, we need to enable trace flag 460 using DBCC TraceOn. This trace flag displays the SQL truncate error message – “String or binary data would be truncated in table ‘%.*ls’, column ‘%.*ls’. Truncated value: ‘%.*ls’.”

在SQL Server 2019中,我们需要使用DBCC TraceOn启用跟踪标志460 。 此跟踪标志显示SQL截断错误消息– “表'%。* ls'的列'%。* ls'中的字符串或二进制数据将被截断。 截断值:“%。* ls”。”

Let us enable the trace flag 460 and run the query.

让我们启用跟踪标志460并运行查询。

Now let us run the insert statement from our script in example 2 with DBCC TRACEON(460)

现在,让我们使用DBCC TRACEON(460)从示例2中的脚本运行插入语句。

解决字符串或二进制数据截断的解决方案 (Solution to fix String or binary data truncation)

Now in SQL Server 2019.we can easily find out the column and data, which caused the issue. In order to fix the issue, we can choose from any of the below solution appropriate to us.

现在在SQL Server 2019中,我们可以轻松找出导致问题的列和数据。 为了解决该问题,我们可以从以下适合我们的解决方案中进行选择。

  • Fix the data that we are trying to insert or update. Data length should not exceed the maximum allowed limit for the particular column 修复我们尝试插入或更新的数据。 数据长度不得超过特定列的最大允许限制
  • Use ‘SET ANSI_WARNINGS OFF’ to truncate the data and insert it as per column maximum string length 使用“ SET ANSI_WARNINGS OFF”截断数据并根据列的最大字符串长度插入

In the below example used ‘ SET ANSI_WARNINGS off’. Therefore, SQL Server will truncate the data as needed to make it fit into the column. We will not get any SQL truncate error as well since data is truncated and inserted into the table.

在下面的示例中,使用了' SET ANSI_WARNINGS off'。 因此,SQL Server将根据需要截断数据以使其适合列。 由于数据会被截断并插入到表中,因此我们也不会收到任何SQL截断错误。

We can see the SQL Server inserts data as fit into the column data size. For example, ‘SQLShack ApexSQL Community’ inserted to the table after truncation as ‘SQLShack A’

我们可以看到SQL Server插入的数据适合列数据大小。 例如,截断后将“ SQLShack ApexSQL社区”作为“ SQLShack A”插入表中

  • Modify the column using the alter table statement 使用alter table语句修改列

We can also modify the column property to allow more string length data. We can use the below query to alter table.

我们还可以修改column属性以允许更多的字符串长度数据。 我们可以使用下面的查询来更改表。

ALTER TABLE [TableName] ALTER COLUMN [Column_name] datatype(value)

In the below example, we modified the column [CustomerName] to varchar (50) from varchar(30) and executed the example 2 query. This time it executes successfully.

在下面的示例中,我们将[CustomerName]列从varchar(30)修改为varchar(50),并执行了示例2查询。 这次它成功执行了。

结论 (Conclusion)

Silent data truncation in SQL Server 2019 is a really nice enhancement. This will make many database administrators and developers happy with this detailed SQL truncate error message. Currently, we have to enable the trace flag in SQL Server 2019. I believe this feature will be available without trace flag as well in an upcoming release.

SQL Server 2019中的静音数据截断是一项非常不错的增强功能。 这将使许多数据库管理员和开发人员对这个详细SQL截断错误消息感到满意。 当前,我们必须在SQL Server 2019中启用跟踪标记。我相信在即将发布的版本中,也可以使用没有跟踪标记的功能。

翻译自: https://www.sqlshack.com/sql-truncate-enhancement-silent-data-truncation-in-sql-server-2019/

SQL截断增强功能:SQL Server 2019中的静默数据截断相关推荐

  1. SQL Server 2019中的图形数据库功能–第1部分

    SQL Server 2017 introduced Graph database features where we can represent the complex relationship o ...

  2. SQL Server 2019中的证书管理

    介绍 (Introduction) Certificate Management in SQL Server 2019 has been enhanced a lot when compared wi ...

  3. SQL Server 2019中的行模式内存授予反馈

    In this article, I'll be exploring another new feature with SQL Server 2019, row mode memory grant f ...

  4. SQL Server 2019中SQL表变量延迟编译

    In an article, An overview of the SQL table variable, we explored the usage of SQL table variables i ...

  5. 如何在SQL Server 2019中添加数据敏感度分类的命令

    作者 | Jordan Sanders 翻译 | 火火酱.责编 | 晋兆雨 头图 | CSDN付费下载于视觉中国 为了确保数据库安全性和完整性,数据库管理员日常需要运行多种操作.因此,无论在何种情况下 ...

  6. 清空SQL Server数据库中所有表数据的方法(转)

    清空SQL Server数据库中所有表数据的方法 其实删除数据库中数据的方法并不复杂,为什么我还要多此一举呢,一是我这里介绍的是删除数据库的所有数据,因为数据之间可能形成相互约束关系,删除操作可能陷入 ...

  7. 2019服务器部署文件管理,在 Windows Server 2019 中部署文件共享见证 | Microsoft Docs

    部署文件共享见证 05/28/2021 本文内容 适用于: Windows Server 2022,Azure Stack HCI,版本 20H2;Windows服务器2019.Windows Ser ...

  8. wsl 重启_漫谈在Windows Server 2019中安装使用WSL

    熟悉IT历史的朋友一定不会忘记98蓝屏事件:时任微软CEO的比尔·盖茨和助理 Chris Capossela在1998年春季计算机分销商展会(COMDEX )现场演示Windows 98的" ...

  9. window启用无线服务器,如何在Windows Server 2019中启用WiFi

    如何在Windows Server 2019中启用WiFi 在本逐步指南中,了解如何在Windows Server 2019中启用WiFi.默认情况下,服务器上缺少无线功能. 如果您使用的是Windo ...

最新文章

  1. 设置android启动器,教程:在任意 Android 设备上安装 HTC 专属桌面启动器
  2. mysql 关键字 status_Mysql show status命令详解
  3. HDU-5723 Abandoned country
  4. 【指标统计】标记存量遥控(成功/失败)遥信(正确/错误)
  5. Java内存图以及堆、栈、常量区、静态区、方法区的区别
  6. mybatis中,collection配置后查询只显示一条记录
  7. ctguoj-取石头 (15分)
  8. 中文文本拼写检查错误纠正方案整理
  9. Lisp面面观松本行弘谈Lisp元编程
  10. xml转json(dom4j + fastjson)
  11. java poi word 复制_java poi实现word导出(包括word模板的使用、复制表格、复制行、插入图片的使用)...
  12. [堆入门off-by-null]asis2016_b00ks
  13. 手机及电脑的护眼模式开启
  14. excel中单元格的回车替换成其他字符
  15. android界面美化教程,android界面UI美化:沉浸模式、全透明或半透明状态栏及导航栏的实现...
  16. GDCM:SCU验证的测试程序
  17. Java实现模糊搜索
  18. MacBook Pro 把机械硬盘换成固态硬盘
  19. 说说parse_url和正则表达式,在SQL中如何解析字符串
  20. Windows Mobile 6.0 SDK和中文模拟器下载 Windows Mobile 6.5 模拟器(附5.0下载)

热门文章

  1. sql server列转行怎么提高效率_行转列、列转行
  2. UE4 打包C++项目到win32平台报错 could not find mspdbcore.dll
  3. Do Now 一个让你静心学习的APP——团队博客
  4. 让maven项目使用nexus作为远程仓库
  5. 03-dotnet core创建区域[Areas]及后台搭建
  6. 用sed替换文件中的空格
  7. ASP.NET Web API 上传文件
  8. 面试必知的25个经典回答 ,最全的面试干货,没有之一
  9. 你赞同企业年薪百万的高管对员工说别羡慕赚的多,人家加班和付出的时候你在玩的说法吗?
  10. 买了社保,再买农村医保是不是多余?