更新 NULL table 时出现转换数据类型问题

Conversion data type issue when UPDATE a NULL table

我有如下查询:

IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL BEGIN
       drop table #Temp1
end

SELECT * into #Temp1
   from (
          SELECT 1, NULL, NULL, NULL, NULL
UNION ALL SELECT 2, NULL, NULL, NULL, NULL
UNION ALL SELECT 3, NULL, NULL, NULL, NULL
UNION ALL SELECT 4, NULL, NULL, NULL, NULL
UNION ALL SELECT 5, NULL, NULL, NULL, NULL
UNION ALL SELECT 6, NULL, NULL, NULL, NULL
UNION ALL SELECT 7, NULL, NULL, NULL, NULL
UNION ALL SELECT 8, NULL, NULL, NULL, NULL
UNION ALL SELECT 9, NULL, NULL, NULL, NULL
)
as databases (tempid, tasknr, devcat, taskop, taskcl)

IF OBJECT_ID('tempdb..#Temp1a') IS NOT NULL BEGIN
       drop table #Temp1a
end

SELECT * into #Temp1a
   from (
select
cast(ROW_NUMBER() OVER(PARTITION BY parent_change ORDER BY number)as int) as tempid
,number as tasknr
,category as cat
,orig_date_entered as taskop
,case when (CM3TM1.status = 'closed') then CM3TM1.date_entered else NULL end as taskcl
FROM CM3TM1
WHERE parent_change IN ('C45168')
and category = 'NEU Development' 
)
as databases (tempid, tasknr, devcat, taskop, taskcl)


UPDATE
    #Temp1
SET
    #Temp1.tasknr = #Temp1a.tasknr,
    #Temp1.devcat = #Temp1a.devcat
FROM
    #Temp1a
INNER JOIN
    #Temp1
ON
    #Temp1.tempid = #Temp1a.tempid

我得到

Msg 245, Level 16, State 1, Line 38 Conversion failed when converting the varchar value 'T85158' to data type int.

T85158 与 'tasknr' 列相关。

我需要用行数可变的不同类型的数据更新此类 NULL table。我曾尝试添加 ,cast((number) as int) as tasknr 但它没有帮助。 请让我知道如何使它正常工作。

您在创建 #temp1 时没有向 SQL 服务器提供类型信息,因此它(显然)决定每一列的类型都是 int。如果你想拥有特定类型的列,更喜欢显式创建 table:

CREATE TABLE #temp1 (
    tempid int not null,
    tasknr varchar(19) null,
    devcat decimal(13,4) null,
    taskop int null,
    taskcl xml null
)
INSERT INTO #temp1(tempid, tasknr, devcat, taskop, taskcl) VALUES
(1, NULL, NULL, NULL, NULL),
(2, NULL, NULL, NULL, NULL),
(3, NULL, NULL, NULL, NULL),
(4, NULL, NULL, NULL, NULL),
(5, NULL, NULL, NULL, NULL),
(6, NULL, NULL, NULL, NULL),
(7, NULL, NULL, NULL, NULL),
(8, NULL, NULL, NULL, NULL),
(9, NULL, NULL, NULL, NULL)

...

Damien 正确地给出了错误原因。以下是可能修复的另一种形式。 将脚本的上半部分修改为:

SELECT * into #Temp1
   from (
          SELECT 1 tempid, cast (NULL as varchar(19)) tasknr , cast(NULL as decimal(13,4)) devcat, cast(NULL as int) taskop, cast(NULL as xml) taskcl
UNION ALL SELECT 2, NULL, NULL, NULL, NULL
UNION ALL SELECT 3, NULL, NULL, NULL, NULL
UNION ALL SELECT 4, NULL, NULL, NULL, NULL
UNION ALL SELECT 5, NULL, NULL, NULL, NULL
UNION ALL SELECT 6, NULL, NULL, NULL, NULL
UNION ALL SELECT 7, NULL, NULL, NULL, NULL
UNION ALL SELECT 8, NULL, NULL, NULL, NULL
UNION ALL SELECT 9, NULL, NULL, NULL, NULL
)

.......

编辑:DELETE那些每列都为 NULL 的行,请使用此脚本:

DELETE FROM #temp1 WHERE
COALESCE(tasknr,devcat,taskop,taskcl) IS NULL