10

如果您在 SQL Server 中使用“插入”创建临时表,它会使用第一个插入来确定列是否接受空值。如果第一个插入具有空值,则该列可以为空,否则它将不可为空。

有没有办法使用“插入”来创建临时表来接受空值?

例子

这工作没有任何问题

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声明,但我想在不重写数百个现有查询的情况下做到这一点。

4

4 回答 4

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
于 2014-08-11T18:08:33.257 回答
7

我会通过在第一次插入之前显式创建临时表来解决这个问题。

create table #temp (a varchar(10) not null, b int null)
于 2015-08-13T10:59:57.757 回答
0

这是一个老问题,但我有一个类似的问题,我将初始查询 UNION NULLs可能对 OP 有所帮助。

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

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

把它放在这里,下次我需要这样做时忘记如何......

于 2021-06-11T20:58:51.327 回答
0

(不)幸运的是,这个问题太受欢迎了,并且出现在 Sybase ASE 15.7 的顶部,所以只需在此处添加我对 Sybase 的答案。

对我来说,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
于 2020-10-08T14:18:07.450 回答