且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server在存储过程中默默地截断varchar

更新时间:2023-11-19 23:34:58

.

我从来没有注意到一个问题,因为我的一项检查是确保我的参数与我的表列长度匹配.在客户端代码中也是如此.就个人而言,我希望SQL永远不会看到过长的数据.如果我确实看到数据被截断,那会很明显是由什么引起的.

I've never noticed a problem though because one of my checks would be to ensure my parameters match my table column lengths. In the client code too. Personally, I'd expect SQL to never see data that is too long. If I did see truncated data, it'd be bleeding obvious what caused it.

如果由于

If you do feel the need for varchar(max) beware a massive performance issue because of datatype precedence. varchar(max) has higher precedence than varchar(n) (longest is highest). So in this type of query you'll get a scan not a seek and every varchar(100) value is CAST to varchar(max)

UPDATE ...WHERE varchar100column = @varcharmaxvalue

有一个它可能值得包含在 Erland Sommarkog的严格设置(和

And it's probably worthy of inclusion in Erland Sommarkog's Strict settings (and matching Connect item).

在马丁斯发表评论后

DECLARE @sql VARCHAR(MAX), @nsql nVARCHAR(MAX);
SELECT @sql = 'B', @nsql = 'B'; 
SELECT 
   LEN(@sql), 
   LEN(@nsql), 
   DATALENGTH(@sql), 
   DATALENGTH(@nsql)
;

DECLARE @t table(c varchar(8000));
INSERT INTO @t values (replicate('A', 7500));

SELECT LEN(c) from @t;
SELECT 
   LEN(@sql + c), 
   LEN(@nsql + c), 
   DATALENGTH(@sql + c), 
   DATALENGTH(@nsql + c) 
FROM @t;