如何允许临时表接受空值

Smi*_*ith 5 sql null temp-tables sql-server-2008-r2

如果在SQL Server中使用"insert into"创建临时表,则使用第一个插入来确定列是否接受空值.如果第一个插入具有空值,则该列可以为空,否则它将是不可为空的.

有没有办法使用"insert into"创建临时表来接受空值?

这没有任何问题

Select 'one' as a , null as b
into #temp

insert into #temp
Select 'two' as a , 500 as b
Run Code Online (Sandbox Code Playgroud)

但是这会抛出"无法将值NULL插入列'b'"

Select 'one' as a , 500 as b
into #temp

insert into #temp
Select 'two' as a , null as b
Run Code Online (Sandbox Code Playgroud)

我知道我可以做create Tablealter column声明,但我想这样做而不重写数百个现有的查询.

Pio*_*ski 9

我将通过在首次插入之前显式创建临时表来解决此问题。

create table #temp (a varchar(10) not null, b int null)
Run Code Online (Sandbox Code Playgroud)


Rob*_*bin 6

这个怎么样?

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
Run Code Online (Sandbox Code Playgroud)