为什么我在某些情况下会得到"字符串或二进制数据会被截断"?

dwo*_*sch 5 sql-server

我正在解决SQL Server错误消息8152的问题"字符串或二进制数据将被截断"仅在某些情况下.以下查询类似于那个,即抛出错误.

CREATE TABLE SourceValues (
    SourceId INT IDENTITY (1,1),
    SourceValue VARCHAR(3)
)
GO
INSERT INTO SourceValues (SourceValue) VALUES ('aaa')
INSERT INTO SourceValues (SourceValue) VALUES ('aab')
INSERT INTO SourceValues (SourceValue) VALUES ('aa')
INSERT INTO SourceValues (SourceValue) VALUES ('ab')
INSERT INTO SourceValues (SourceValue) VALUES ('a')
INSERT INTO SourceValues (SourceValue) VALUES ('b')
GO

PRINT 'NOT WORKING #1'
CREATE TABLE TargetValues (TargetValue VARCHAR(2))
INSERT INTO TargetValues (TargetValue) 
SELECT s1.SourceValue
FROM SourceValues s1, SourceValues s2
WHERE s1.SourceId=s2.SourceId+1 AND s1.SourceValue!='aab'
DROP TABLE TargetValues
GO

PRINT 'NOT WORKING #2'
CREATE TABLE TargetValues (TargetValue VARCHAR(2))
INSERT INTO TargetValues (TargetValue) 
SELECT s1.SourceValue
FROM SourceValues s1, SourceValues s2
WHERE s1.SourceId=s2.SourceId+1 AND s1.SourceValue!='aab'
ORDER BY s1.SourceValue
DROP TABLE TargetValues
GO

PRINT 'WORKING #1'
CREATE TABLE TargetValues (TargetValue VARCHAR(2))
INSERT INTO TargetValues (TargetValue) 
SELECT s1.SourceValue
FROM SourceValues s1, SourceValues s2
WHERE s1.SourceId=s2.SourceId+1 AND s1.SourceValue!='aab'
ORDER BY s2.SourceValue -- <-- using s2 instead of s1 for order
DROP TABLE TargetValues
GO

PRINT 'WORKING #2'
CREATE TABLE TargetValues (TargetId INT IDENTITY (1,1),TargetValue VARCHAR(2)) -- <-- using identity column
INSERT INTO TargetValues (TargetValue) 
SELECT s1.SourceValue 
FROM SourceValues s1, SourceValues s2 
WHERE s1.SourceId=s2.SourceId+1 AND s1.SourceValue!='aab'
DROP TABLE TargetValues
GO

DROP TABLE SourceValues
Run Code Online (Sandbox Code Playgroud)

查询"NOT WORKING 1"中出现问题,其他问题是关于解决方案的一些想法.有谁知道不工作的查询和工作查询之间的差异?

我在SQL Server 2005,SQL Server 2008和SQL Server 2008 R2上测试了这个并得到了相同的结果.但我听说在另一个SQL Server 2008 R2实例上所有查询都失败了.

请注意,我已经通过将TargetValues表中的varchar设置为3(已更正错误)来解决此问题.

dan*_*ken 1

如果我是对的,您尝试将“aaa”添加到 varchar(2) 字段。这是不可能的,因为数据会被截断。