34

sys.[views]转向键值对以与另一台服务器上的值进行一致性测试。我遇到了返回错误的问题。

消息 8167,第 16 层,状态 1,第 51 行

列“type”的类型与 UNPIVOT 列表中指定的其他列的类型冲突。

询问:

SELECT
sourceUnpivoted.idServer,
sourceUnpivoted.sourceServerName,
sourceUnpivoted.name,
sourceUnpivoted.columnName,
sourceUnpivoted.columnValue
FROM (
SELECT 
CAST('1' AS VARCHAR(255)) AS idServer,
CAST('thisOne' AS VARCHAR(255)) AS sourceServerName,
CAST('theDatabase' AS VARCHAR(255)) AS sourceDatabaseName,
CAST(name AS VARCHAR(255)) AS name,
CAST(object_id AS VARCHAR(255)) AS object_id,
CAST(principal_id AS VARCHAR(255)) AS principal_id,
CAST(schema_id AS VARCHAR(255)) AS schema_id,
CAST(parent_object_id AS VARCHAR(255)) AS parent_object_id,
CAST(type AS VARCHAR(255)) AS type,
CAST(type_desc AS VARCHAR(255)) AS type_desc,
CAST(create_date AS VARCHAR(255)) AS create_date,
CAST(lock_escalation_desc AS VARCHAR(255)) AS lock_escalation_desc
...
FROM noc_test.dbo.stage_sysTables
) AS databaseTables
UNPIVOT (
columnValue FOR columnName IN (
object_id,
principal_id,
schema_id,
parent_object_id,
type,
type_desc,
create_date,
lock_escalation_desc
) 
) AS sourceUnpivoted

为什么这不喜欢[type], [type_desc], [lock_escalation_desc]??? 我也试过CONVERT(VARCHAR(255),type) AS type

4

5 回答 5

40

这实际上是一个排序问题。我可以通过更改这些行来解决它:

CAST([type] collate database_default AS VARCHAR(255)) AS [type], 
CAST(type_desc collate database_default AS VARCHAR(255)) AS type_desc, 
CAST(create_date AS VARCHAR(255)) AS create_date, 
CAST(lock_escalation_desc collate database_default AS VARCHAR(255)) AS lock_escalation_desc 

具体问题是name排序为Latin1_General_CI_AS,而您提到的其他 3 列被排序为Latin1_General_CI_AS_KS_WS(至少,在我的机器上,我不确定在具有不同默认排序规则的服务器/数据库上会是什么样子)。

于 2012-06-22T14:24:45.387 回答
26

这是此类型错误的解决方案之一

1:创建此表

CREATE TABLE People
(
PersonId int, 
Firstname varchar(50), 
Lastname varchar(25)
)

2:然后插入

INSERT INTO People VALUES (1, 'Jim', 'Smith');
INSERT INTO People VALUES (2, 'Jane', 'Jones');
INSERT INTO People VALUES (3, 'Bob', 'Unicorn');

3:运行这个脚本你得到错误

消息 8167,级别 16,状态 1,第 3 行“姓氏”列的类型与 UNPIVOT 列表中指定的其他列的类型冲突。

SELECT PersonId, ColumnName, Value
FROM People
unpivot(Value FOR ColumnName IN (FirstName, LastName)) unpiv;

4:解决方案是您必须使用子查询首先将 Lastname 列强制转换为与 Firstname 相同的长度

SELECT PersonId, ColumnName, Value
FROM (
SELECT personid, firstname, cast(lastname AS VARCHAR(50)) lastname
FROM People
) d
unpivot(Value FOR ColumnName IN (FirstName, LastName)) unpiv;
于 2014-07-08T14:09:40.223 回答
5

遇到同样的错误,我只是将表中的所有列都设为相同的数据类型——我混合了不同长度的int, varchar, nvarchar。一旦我将表中的所有列都转换为相同的类型 -nvarchar(255)它工作得很好。

于 2017-09-13T17:33:17.100 回答
4

PIVOT/UNPIVOT 子句对列的 ANSI 填充状态(右键单击 -> SSMS 中的属性)以及类型、大小和排序规则敏感。在添加或重新创建有问题的列之前,尝试在会话中指定 SET ANSI_PADDING ON|OFF,以便它与 PIVOT/UNPIVOT 子句中的其他列匹配。

于 2015-08-03T10:21:25.230 回答
4

我遇到过同样的问题。通过右键单击列标题并选择更改类型“使用区域设置”来修复它。请参阅随附的屏幕截图

1截屏

于 2018-05-05T09:59:14.433 回答