sql2015
sql2015

Reputation: 611

SQL Server insert into next column

SQL Server 2012: is it possible to do a insert into select statement but insert data into the next column if the previous is already populated?

I have a table with a number of columns to store dates, I want to take data from another table and insert into the next available null date column.

Upvotes: 0

Views: 292

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522299

If you are saying that the previous column is already populated, then you're really looking for some sort of update. Try this:

UPDATE yourTable
SET
    col1 = CASE WHEN col1 IS NULL THEN 'value' ELSE col1 END,
    col2 = CASE WHEN col1 IS NOT NULL THEN 'value' ELSE col2 END;

The logic here is what you described, namely that we attempt to update col1 with some value. Should that column be empty, we make the update, otherwise we update col2 instead.

Upvotes: 3

Related Questions