SQL Server – How to Execute a Query Based on Column Existence

sql serversql-server-2008sql-server-2008-r2

I want to run the following query:

CREATE TABLE dummy AS
SELECT x, y, z
FROM table1
WHERE y!=0

then I want to do the following:

if z column has a non-null entry do:
1. copy the content of z into A
2. drop z
SELECT x,A
FROM Dummy 

What the second query essentially tries to do is that copy those rows of z into A which have no missing values.
My question is how can we write query 2 and if there is a way to merge these two queries into one for optimisation?

Any help/advice much appreciated.

Best Answer

Since you aren't using column y, you can ignore it in your first query. Then, you can simplify this with a single statement:

SELECT 
    x, 
    A = z
FROM table1
WHERE y!=0 and z is not null