Insert into table with auto-increment field - sql-server-2008

I have two tables called HRData and HRDataHistory. HRDataHistory has the same structure as HRData except the first column is an autoincrement field and the last column is a DateTime field.
HRData has a trigger:
CREATE TRIGGER [HR].[HRData_History]
ON [HR].[HRData]
AFTER INSERT, UPDATE
AS
INSERT INTO HR.HRDataHistory
SELECT *, GETDATE()
FROM inserted
;
GO
This is working on an existing development machine. I am trying to mirror this relationship on my local sql server instance so that I can test some changes. Using SSMS I used 'Script Table as Create To...' and created the structure of each table and index on my local sql server instance. However when I do this for the trigger I get the following error:
An explicit value for the identity column in table 'HR.HRDataHistory' can only be specified when a column list is used and IDENTITY_INSERT is ON.
I know the preferred method would be to specify the columns, but I want to mirror production which does not currently do that and further I want to understand why it is working in production but not on my test database.

You're getting this error because you're trying to insert data into an IDENTITY column, which auto-populates itself whenever you insert another row in that table.
Off the top of my head, you can do something like below (although I believe there are more elegant solutions and I do not guarantee that this is a safe solution, nor have I tried something like this and I recommend testing on a TEST database before trying in production/LIVE):
add another column to HRDataHistory table which does not have identity set on it (because you cannot remove identity form a colum once set), but must have the same datatype as the current ID (IDENTITY) column
use a UPDATE query to move all of your ID's from your IDENTITY column to your new column:
UPDATE HRDataHistory
SET new_column = ID
Drop the IDENTITY column (but this might have grave implications if you have any FK set on it and possibly other objects that use it):
ALTER TABLE HRDataHistory
DROP COLUMN ID
Rename the "new_column" to the name of your previous IDENTITY column:
EXEC sp_RENAME 'HRDataHistory.new_column' , 'ID', 'COLUMN'
At this point I believe you can use your trigger to "copy" the newly inserted data from the HRData table into the HRDataHistory, since the column names should match and there is no more conflict due to IDENTITY.
Again, this might (not guaranteed) work so I recommend you first check on a TEST environment.

Related

Create Column in MySql on Insert

I have devoted a long time of my career on MySQL and recently shifted to MongoDB. On of the very fine feature about MongoDB is that we don't need to alter or create columns on Collection/Table specifically. The column will be created as we insert Data. For e.g., If we have a collection/table named as Emp in MongoDb, I can pass an object to it like:
{
id:12,
name:'abc',
phone:8298999
}
If Emp doesn't has column phone or any other, it will not report an error, rather the missing column will be created automatically on insert, and previous records will hold a default null value for newly created column.
Does such functionality exists in MySQL? To summarize, while Inserting a new record in MySQL table, if a column doesn't exists in table and is mentioned in INSERT query, can that missing column be automatically created with a default value?

Update all rows of a single column from one table to the same table in another database

Ok, so I have a database in my testing environment called 'Food'. In this database, there is a table called 'recipe', with a column called 'source'.
This same database exists in my local environment. However, I just received an updated database (in my local environment) where all the column values (for 'source') have changed.
Is there any way I can migrate the 'source' column from my local to my test environment, without changing the values for any other column? There are 1186 rows in the 'Food' database 'recipe' table in my test environment that need to be updated ONLY with the 'source' column.
You need some way to uniquely identify your Recipes. If both tables have a surrogate key that remained constant, use that. Otherwise figure out some way to match up the new data with your test data: you might already have a unique index in mind or you might need to decide on a combination of fields that uniquely identify your Recipes.
On a side note, why can't you just overwrite all the columns? It is just test data, right?
If only a column has changed and you have IDs (or keys) on your rows, you could follow these steps:
create an intermediate table locally
insert keys and new source values there (either those which have changed or all)
use mysqldump to selectively export the table from the local database
copy the dumped table to the remote database server
import it there
join it with the production table in an update statement to replace the values
drop the intermediate table on the server

how to update the value of one table when the value is inserted in another table using mysql?

hi i have two tables namely
sms(Message,sms_index...columns)
c_paid_bribe(c_addi_info,....)
what i want to do is to insert the values of Message column of sms table into c_addi_info column of c_paid_bribe table automatically whenever a new value is inserted into sms table.
I tried this
$query=mysql_query("insert into bd_paid_bribe(c_addi_info) select Message from sms");
But when a new value is inserted and i run the .php file the already existed values are also inserting into the table again.....
Q: what i want to do is to insert the values of Message column of sms table into c_addi_info column of c_paid_bribe table automatically whenever a new value is inserted into sms table.
A: If you want to update one table when another is changed (and, for whatever reason, you can't simply do this in your application), then use "triggers":
http://net.tutsplus.com/tutorials/databases/introduction-to-mysql-triggers/
Q: But when a new value is inserted and i run the .php file the already existed values are also inserting into the table again.....
A: You want an "upsert". For example:
How do I update if exists, insert if not (AKA "upsert" or "merge") in MySQL?
What you want to do is simply to make two queries that are comitted in one transaction. This is what transactions are for. See here for examples on how to do it:
PHP + MySQL transactions examples

How to increment the Identity column

I am using identity columns as a primary key in my tables.
In some situations I need to work with primary keys before inserting a new row.
For example, in Oracle I use : select <sequence_name>.nextval into <variable> from dual
and I was sure that no one will insert any row with the same ID while my sp was executing.
As for SQL Server I can read the current identity value and it's increment, but there is no way to increment it without inserting a row.
Updated: The question is - how can I accomplish my task to work with ID (as identity column) in SQL Server before inserting a row and be sure that it will be unique at the end of my stored procedure.
Updated:I have a table with HierarchyId column.The way to form the first level of hierarchy,in my case, is to insert the hierarchyId column, according to indentity column. That is how I'v done it now:
begin transaction
insert into [dbo].[Group](GroupTypeId,CompanyOwnerId,GroupHierarchyId)
values(#GroupTypeId,#HeaderCompanyId,null)
update [dbo].[Group]
set GroupHierarcyId=hierarchyid::GetRoot().GetDescendant(cast ('/'+cast(#NewGroupId as varchar)+'/' as hierarchyid),null)
where GroupId=scope_identity()
commit
You can put an exclusive lock on the table, get the maximum ID, add 1 to it. That will be your next ID. Insert your data, the unlock the table.
HOWEVER,
I cannot fathom why you would want to work with a value before it is created. Can yo post a bit more information on that?
If you need a key that would be unique across databases and database servers, then the GUID's (Global Unique Identifier) certainly fulfills this need.
If you want to generate a new GUID server the you can simply use the NEWID() function
SELECT NEWID()

How do you assign a column default in MySQL to another column's value?

I want to add a new column to a table in MySQL database that should get the value of another column in the same table. Is this possible? If so, how do you do it?
Starting with MySQL 5.0.2 you can write a stored procedure linked to a TRIGGER which can examine the new column each time a row is inserted, and automatically copy the other column's value into the new column if no value was supplied for the new column.
You Can use this following two command to do your work.
This command will be used to add new column in you table. Remember data type from where you want to copy to use those data type in new Column.
ALTER TABLE table_name ADD new_column_name VARCHAR(60);
2: This command to copy data from old column name to new column name.
UPDATE table_name SET new_column_name = old_column_name;
Then if you want to delete previous column, Then you can use following command
ALTER TABLE table_name DROP COLUMN old_column_name;
As of 20101212 mysql does not support defaulting 2 timestamp columns, which means you can't do a 'created' and 'updated' on the same table.
If this is what you were trying to do, then the trigger with the stored proc is the way to go.
create a view, and you can select the same column twice and give it different name, then the application can use the view instead use the table directly.