tags:

views:

152

answers:

2

I'm copying a subset of some data, so that the copy will be independently modifiable in future.

One of my SQL statements looks something like this (I've changed table and column names):

INSERT Product(
  ProductRangeID,
  Name, Weight, Price, Color, And, So, On
)
SELECT
  @newrangeid AS ProductRangeID,
  Name, Weight, Price, Color, And, So, On
FROM Product
WHERE ProductRangeID = @oldrangeid and Color = 'Blue'

That is, we're launching a new product range which initially just consists of all the blue items in some specified current range, under new SKUs. In future we may change the "blue-range" versions of the products independently of the old ones.

I'm pretty new at SQL: is there something clever I should do to avoid listing all those columns, or at least avoid listing them twice? I can live with the current code, but I'd rather not have to come back and modify it if new columns are added to Product. In its current form it would just silently fail to copy the new column if I forget to do that, which should show up in testing but isn't great.

I am copying every column except for the ProductRangeID (which I modify), the ProductID (incrementing primary key) and two DateCreated and timestamp columns (which take their auto-generated values for the new row).

Btw, I suspect I should probably have a separate join table between ProductID and ProductRangeID. I didn't define the tables.

This is in a T-SQL stored procedure on SQL Server 2008, if that makes any difference.

+1  A: 

In a SELECT, you can either use * or list all columns and expressions explicitly, there are no partial wildcards.

You could possibly do a SELECT * into a temporary table or a table variable followed by an UPDATE of that table if that is just an one-off query and performance is of no importance.

Quassnoi
Indeed performance isn't important. Are you saying I `select *` into a table variable, then drop columns from the table variable, and update the rangeid? Then can I insert from that table into Product without listing the columns?
Steve Jessop
@Steve: yes, except that you cannot drop columns from a table variable, only from a temporary table.
Quassnoi
+1  A: 

You can omit the field names for the target table, but generally you shouldn't.

If you don't specify the fields for the target table, you will be relying on the order that they are defined in the table. If someone changes that order, the query will stop working. Or ever worse, it can put the values in the wrong field.

Another aspect is that it's easier to see what the query does, so that you don't have to open the table to see what the fields are to understand the query.

Guffa
Fair enough. In fact, I'm relying on the fields in the table even listing them. If a new field is added, most likely I'll want to copy it, meaning that the query will stop "working". I'm willing to neglect the risk of the fields changing *order* without any being added or removed...
Steve Jessop