如何允许临时表接受空值

11
如果您在SQL Server中使用“insert into”创建临时表,它将使用第一个插入来确定列是否接受null值。如果第一个插入具有null值,则该列变为可空,否则它将是不可空的。
是否有一种方法可以使用“insert into”创建临时表来接受null值?
示例
这个没有任何问题。
Select 'one' as a , null as b
into #temp

insert into #temp
Select 'two' as a , 500 as b

然而,这会抛出“无法将值NULL插入列'b'”的错误。
Select 'one' as a , 500 as b
into #temp

insert into #temp
Select 'two' as a , null as b

我知道我可以使用create Tablealter column语句,但我想在不重写数百个现有查询的情况下完成它。

1
可能是重复的问题 - https://dev59.com/c2035IYBdhLWcg3wW-z1 - steoleary
@Serg 是的,它会起作用,但那是解决这个问题的错误方法。 - Smith
为什么要顶一下?这个问题已经在上面的重复链接中得到了回答。 - Martin Smith
@Martin 实际上不是这样的,重复的链接建议重写,但我正在寻找一种不需要重写的方法。 - Smith
@Serg 我不知道正确的解决方案,但插入记录不是正确的方法。 - Smith
显示剩余5条评论
4个回答

9
我会通过在第一次插入之前明确地创建临时表来解决这个问题。
create table #temp (a varchar(10) not null, b int null)

8
这个怎么样?
Select CONVERT(varchar(100), 'one') as a , CONVERT(int, 500) as b
into #temp

insert into #temp
Select 'two' as a , null as b

select * from #temp order by 1

0

这是一个老问题,但我遇到了类似的问题,我将NULL联合到初始查询中,这可能有助于OP。

Select 'one' as a , 500 as b
into #temp
UNION
SELECT NULL, NULL

insert into #temp
Select 'two' as a , NULL as b

把它放在这里,这样下次我需要做这个并且忘记了怎么做...


0

(不)幸的是,这个问题在Sybase ASE 15.7中也非常流行,并且排名靠前,因此我在这里添加了我的答案。

对于我来说,无论是cast、convert还是coalesce都不起作用,但是case语句可以解决问题(这就是coalesce的作用,但是呃...)

select
    a = case when 1 = 0 then null else 'one' end, 
    b = case when 1 = 0 null else 500 end 
into #temp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接