Casting NULL

I ran into something at work last week with selecting records into a new table.

select 
1 as RecordNumber,
'Record1' as DisplayName,
getdate() as CreatedDate,
null as TestColumn
into dbo.TestTable1

NULL was used as a value for a column that wouldn’t be filled at creation time but would be set in a later operation. In this example, TestColumn is created as an int column. So most likely, you would want a different data type for the column. So one option would be not to create TestColumn initially but create the column explicitly with an ALTER TABLE command.
If you insisted on having the column present at creation time, one option would be to cast the NULL to a specific data type.

select 
1 as RecordNumber,
'Record1' as DisplayName,
getdate() as CreatedDate,
cast(null as varchar(25)) as TestColumn
into dbo.TestTable2

In this case, TestColumn will be created as a varchar(25).
I’m not sure how useful this is, but it had never occurred to me to try to cast a NULL before.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: