trigger in sql server 2005 - sql-server

I want to create trigger for one table for insertion...If i insert records in one table then that same records should be inserted to another one......how?
and also explain about triggers

All you need to know about triggers, without having to wade through Microsoft speak, including how to create them in SQL Server.
http://en.wikipedia.org/wiki/Database_trigger

It should be something like
CREATE TRIGGER TableInserted ON TableInsert
AFTER INSERT
AS
INSERT INTO OtherTable SELECT * FROM inserted

This article covers all the basics of creating triggers.
Though for you task i think a stored procedure doing both inserts will be better, because what if one insert succeeded and the other failed? it will create inconsistency in your data. See here for stored procedures.

Related

how to create a rollback copy of a table just in case i do wrong insert or update

Hi i' d like to know is there any way to create a rollback copy of a table in SQL server just in case i do wrong insert or update statement i'd like to recover my data as it was before that insert or update statements.
SELECT *
INTO myBackupTableName
FROM Yourtable
Creates a backup of the table.
Assuming that we are discussing a production environment and workload: The more I think about this question/requirement the more strongly I believe rollback is the best answer.
Summarizing suggestions already made:
Select into to create a backup table will create a copy of the table but if you revert to it you will potentially be losing data from other users or batches.
Using the into clause from a select or update statement will get you the changed rows but not the original value.
Another answer would be to create an audit table and use a trigger to populate it. Your audit table would need to include enough details regarding the batch to identify it for rollback. This could end up being quite a rabbit hole. Once you have the trigger on the base table and the audit table you will then need to create the code to use this audit table to revert your batch. The trigger could become a performance issue and if the database has enough changes from enough other users then you still would not be able to revert your batch without possibly losing other users' work.
You can wrap your update AND your validation code inside the same proc and if the validation fails only your changes are rolled back.
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/begin-transaction-transact-sql
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/rollback-transaction-transact-sql

Adding insert into linked server inside a trigger

I'm trying to run a trigger that allows me to insert the inserted data on my local table to the linked server's table. This is what I did:
use [medb]
ALTER TRIGGER [dbo].[trigger1] ON [dbo].[tbl1]
AFTER INSERT
AS
BEGIN
INSERT into openquery(DEV, 'tbl_remotetbl') select * from inserted
END
but it is giving this error:
Cannot process the object "tbl_remotetbl". The OLE DB provider
"MSDASQL" for linked server "DEV" indicates that either the object has
no columns or the current user does not have permissions on that
object.
What seems to be my problem?
Note: I am using SQL Server 2008 R2
Did you try running the command outside the trigger ? Did it work ?
here is the syntax I'm using in my openquery:
INSERT INTO OPENQUERY(LinkedServer_Name,
'select remote_field_1,remote_field_2 from remote_Schema.remote_table')
select local_column1,local_column2
FROM local_Table
Now, with that being said, making this statement work inside a trigger, is something I couldn't do. Above statement woks perfectly when executed by it self. But once it is placed in a trigger, the entire transaction related to that trigger fails. I mean even the insert statement that fires the trigger does not go through, and the main table does not insert the data which was meant to be inserted in it.
i ran into the same issue, and spent many hours trying to figure out how to make an openquery statement work inside update/insert/delete triggers, with no success....
so, here's an alternate solution, maybe this can fix your issue, this is in a scenario where i need to pass data from MSSQL to a MySQL DB.
first, create a holding table, so you can store temporary info that's inserted into a table that will only hold data that i need to pass to MySQL
create table holding_table (ID int, value2 int)
trigger will insert data to the holding table, instead of sending it directly to MySQL
ALTER TRIGGER [dbo].[temp_data_to_mysql]
ON [dbo].[source_table]
FOR insert
AS
BEGIN
INSERT into holding_table (ID,Stock)select a, b from inserted
END
GO
after that, you can just create a task in the SQL server agent, so it can execute your stored procedure every N minutes.
hope it helps, im aware that this is a workaround, but after some investigation and testing, i was unable to make openquery work called within a trigger process..

Bulk insert. What is it really?

I was doing some reading and research for some things I'm working on. I know what bulk inserts do and how to do them. Though i am at a block. Using sql triggers you can do some cool things on insert. But what happens on bulk insert. Mainly. does the bulk insert do something like this in plain context
Insert into table values('some value')--->sql triger
Insert into table values('some value')--->sql triger
Insert into table values('some value')--->sql triger
and so on.
in which case, after every line a trigger for insert will fire off and sql will wait until thats done until the next line is reached.
I did a bit of reading here on bulk inserts and found that it will always be better. But how does this affect triggers for insert? Apologies for any bad explanations or anything.
As it is documented, triggers do not run on bulk insert.
But you can bulk insert into a temp table, then do a INSERT INTO SELECT FROM TEMP TABLE and you get all advantages on both - fast upload and triggers etc. running.
If you do C# then this also avoids the horrific locking code in the SqlBulkCopy class (on the table).
In SQL, triggers on tables can execute either per row or per statement. The behaviour you are describing is characteristic of triggers that execute per row but SQL Server's flavour of SQL (called Transact-SQL) does not support them. There are only per-statement triggers in SQL Server.
In addition, if by "bulk insert" you mean the specific BULK INSERT statement of Transact-SQL, then what TomTom has said in his answer is almost true: triggers do not execute on BULK INSERT by default. You can specify that they do by adding the FIRE_TRIGGERS clause, and in that case each insert trigger will execute once per statement, as has already been explained.

sql server trigger for insert

I am new to Sql Server but I have always used Oracle a lot. I see that some functionalities are not suppported in Sql Server. Lets say, I want to watch a table for insertion, and what is inserted into that table, I want to copy that same inserted row into another table.
here is my code
Create TRIGGER Post_Trigger ON Posts For Insert
AS
INSERT INTO EmailQueueRaw (UserID,CreatedBy,EmailTypeId,EmailTablePrimaryKey) VALUES('','Arif','1','1');
GO
In Oracle, I used to use New and Old function which are great. But we dont have it in Sql Server and I am not sure what to do here. Please help me how to copy the same data to another table?
You would use INSERTED (and, if needed DELETED) but you need to be aware that they are pseudo-tables and could contain 0, 1, or multiple rows:
Create TRIGGER Post_Trigger ON Posts For Insert
AS
INSERT INTO EmailQueueRaw (UserID,CreatedBy,EmailTypeId,EmailTablePrimaryKey)
SELECT '',ColumnA,'1',ColumnB FROM inserted;
GO

Get schema of proc's select output

I'd like to put the results of a stored proc into a temp table. It seems that the temp table must be defined beforehand and an INSERT INTO will not work.
Anyone know how to get the schema of the recordset being returned from a select statement?
sp_help only gets info on parameters.
You should be able to insert into a temp table without defining the schema using OPENQUERY:
SELECT * INTO #TempTable
FROM OPENQUERY(ServerName, ‘EXEC DataBaseName.dbo.StoredProcedureName paramvalues1, paramvalues1′)
Where ServerName is the name of your Sql Server instance. See this article for more info
Sometimes you just need to know the schema without creating a table. This command outputs the structure of the resultset without actually executing the stored procedure.
From rachmann on 16 April, 2015 from the Microsoft SQL Server forum article How to get schema of resultset returned by a stored procedure without using OPENQUERY?:
SELECT * FROM sys.dm_exec_describe_first_result_set ('owner.sprocName', NULL, 0) ;
Can you execute the logical content including INSERT INTO in a query window? That should generate a temp table that you can use as a model.
Worst case you build the schema by hand, once, which shouldn't be onerous if you are the one writing the SP.
For the benefit of future documentation, I like to hand-craft DDL in SPs anyway. It helps when debugging to have the schema explicitly at hand.
If you are able, change the stored procedure into a user-defined function.
http://www.scottstonehouse.ca/blog/2007/03/stored-procedures-are-not-parameterized.html

Resources