Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create #temp using SELECT INTO with desired data type

For this simple statement:

Select NULL as Col INTO #temp

The default datatype for NULL column is int, if I want to avoid creating # tables ahead and not using table variables, is there any way to default the NULL column as varchar when using SELECT INTO clause?

Thanks

like image 531
LONG Avatar asked Mar 27 '26 22:03

LONG


2 Answers

Just CAST it.

Select CAST(NULL AS VARCHAR(30)) as Col 
INTO #temp

There's no way of doing this as an implicit default for bare NULLs.

like image 78
Martin Smith Avatar answered Mar 29 '26 19:03

Martin Smith


The answers provided should suffice. I do this a lot; here's a few SELECT INTO techniques that I have found helpful (note my inline comments):

if object_id('tempdb..#t1') is not null drop table #t1;
select 
  someid   = identity(int,1,1),          -- add an identity column 
  someTxt1 = cast('xxx' as varchar(10)), -- set the datatype
  someTxt2 = isnull(cast(555 as int), 0) -- set the column as not nullable
into #sometable;
like image 43
Alan Burstein Avatar answered Mar 29 '26 21:03

Alan Burstein