0

所以,我有一个抛出错误的 CTE:Msg 8114, Level 16, State 5, Line 1 Error converting data type nvarchar to float. 问题是,如果我将 CTE 分解为临时表,一切运行正常!

下面是对我正在做的事情的轻微简化(数据类型是准确的,我只是重命名了一些东西,创建了虚假数据,删除了几个额外的连接以及似乎不会影响错误的 where 子句等)......请注意,此示例确实可以正常工作,这只会增加我的困惑:

--Build and populate sample data
create table vals
(
    groupID int,
    valName nvarchar(50),
    val     nvarchar(50)
)
insert into vals(groupID, valName, val)
select 1, 'setting1', '12:00' union
select 1, 'setting2', '18:00' union
select 1, 'setting3', '3.2' union
select 2, 'setting1', '9:00' union
select 2, 'setting3', '4' union
select 2, 'setting5', 'steve'

create table collected
(
    groupID int,
    timeUTC datetime,
    collected float
)
insert into collected(groupID, timeUTC, collected)
select 1, '2012-09-12 18:00', 2.8 union
select 1, '2012-09-12 18:30', 3.0 union
select 1, '2012-09-12 19:00', 3.3 union
select 1, '2012-09-12 19:30', 4.0 union
select 1, '2012-09-12 20:00', 2.5 union
select 2, '2012-09-12 18:00', 3.5 union
select 2, '2012-09-12 18:30', 3.9 union
select 2, '2012-09-12 19:00', 4.6 union
select 2, '2012-09-12 19:30', 4.2 union
select 2, '2012-09-12 20:00', 4.3


--Here's the CTE that errors on the actual dataset
;with triggerVal as (
    select groupID,
        [trg] = min(cast(val as float))
    from vals
    where valName = 'setting3'
    group by groupID
), currentVal as (
    select c.groupID, c.timeUTC,
        [curr] = c.collected
    from collected c
        join (
            select groupID, [lastTime] = max(timeUTC)
            from collected
            group by groupID
        ) l on c.groupID=l.groupID
            and c.timeUTC = l.lastTime
)
select t.groupID, c.timeUTC, t.trg, c.curr
from triggerVal t
    join currentVal c on t.groupID=c.groupID

同样,在我的实时数据中,如果我将上述 CTE 分解为临时表 (#triggerVal#currentVal),一切运行正常。虽然修改代码对我来说并不是世界末日,但我真的很想了解发生了什么!

4

0 回答 0