Q: I need to do an INSERT INTO in one table from a SELECT, but one of the columns of the inserted table is a field that needs to be incremented by one - depending of a key of a “father” related file. For example, I have master-detail files, in each master register I need to begin counting from 1 up to the number of records inside of a MASTER file, when the KEY of master file is changed the child file needs to restart counting from 1 again, how I do the SELECT of this column?
Bryan Oliver says:
You should probably put an IDENTITY attribute on the column of the inserted table. Then you can simple ignore that column in your INSERT statement.
If, on the other hand, you are not allowed to do this for some reason, try this:
UPDATE my_table
SET a = my_col1,
SET b = my_col2,
SET c = ((SELECT MAX(my_val) FROM master_table) + 1) ,
SET d = my_col3
FROM master_table
JOIN my_table.my_val = master_table.my_val
If you are inserting data from some other source to a table with an identity column and you need to ensure you retain the indentity values, you can temporarily allow inserts to the indentity column. Without doing so explicitly you will receive an error if you attempt to insert a value into the indentity column. For example, if I have a table named MYTABLE and I want to allow inserts into it’s identity column, I can execute the following:
set identity_insert mytable on
Once you execute the command you will be able to insert values into the table’s identity column. This will stay in effect in until you turn it off by executing the following:
set identity_insert mytable off
Be aware that at any time, only a single table in a session can have the identity_insert set to on. If you attempt to enable this for a table and another table already has this enabled, you will receive an error and will not be able to do so until you first turn this off for the other table. Also, if the value used for the indentity is larger than the current identity value then the new value will be used for the identity seed for the column.
WHERE ….
I hope that helps.
Technorati Tags: database development, file dependencies, object dependencies, sql server