SQL adding new columns to query

Sometimes a table has all the fields you need and sometimes it doesn’t. I sometimes need to create flag fields or summary fields to hold additional information. So here are the methods I use.

Add a 1 char flag field
select *, ' ' as myflag from table...

Add a column with more than one character or a data type
select *, cast('' as varchar(10)) as mytextfield, cast('' as datetime) as mydatefield from table...

Add several columns using alter
Select * into #mytemptable from table...
Alter table #mytemptable
Add ( col1 varchar(10) null,
col2 datetime null,
col3 int null,
col4 char(1) null
)

Summary field
select units, price, unitsxprice as extended price from table...

Concatenated field
select firstname+" "+lastname as name from table...

Syntax may vary slightly depending on database.

Cup size   
Select size then click on coffee cup.
This entry was posted in Code, Snippets, SQL. Bookmark the permalink.