列与unpivot列表中的其他列的类型冲突

时间:2012-06-22 14:19:00

标签: sql sql-server-2008 tsql

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

  

Msg 8167,Level 16,State 1,Line 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

5 个答案:

答案 0 :(得分:29)

这实际上是整理问题。我可以通过更改这些行来解决它:

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(至少在我的机器上,我不确定在具有不同默认排序规则的服务器/数据库上会是什么样子。)

答案 1 :(得分:16)

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

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:运行此脚本会出现错误

Msg 8167,Level 16,State 1,Line 3 “Lastname”列的类型与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;

答案 2 :(得分:4)

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

答案 3 :(得分:2)

进入同样的错误,我只是在表格中创建了相同数据类型的所有列 - 我混合了各种长度的intvarcharnvarchar。一旦我将表格中的所有列转换为相同的类型 - nvarchar(255),它就能完美地运行。

答案 4 :(得分:0)

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

1Screen shot