How to allow temporary tables to accept null values

五迷三道 提交于 2020-12-08 10:52:34

问题


If you create temp tables using "insert into" in SQL Server it uses the first insert to determine whether a column accepts null value or not. if the first insert has null value the column become nullable otherwise it will be non-nullable.

Is there a way to create temp tables using "insert into" to accept null values?

Example

This works without any problem

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

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

However this throws "Cannot insert the value NULL into column 'b'"

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

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

I know I could do create Table or alter column statement but I want to do it without rewriting hundreds of the existing queries.


回答1:


How about this?

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



回答2:


I would workaround this by explicitly creating temporary table before first insert.

create table #temp (a varchar(10) not null, b int null)



回答3:


(Un)fortunately, this question is too popular and appears at the top for Sybase ASE 15.7 as well, so just adding my answer for Sybase here.

For me neither of cast, convert or coalesce worked, but a case statement did (which is what coalesce is, but eh...)

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


来源:https://stackoverflow.com/questions/15264645/how-to-allow-temporary-tables-to-accept-null-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!