I am confused that what is the on database in the below trigger what is the purpose of using that please let me know what is the use of that
create trigger trmyfirsttrigger
on database
for create_table,alter_table,drop_table
as
begin
rollback
print 'you can not create ,alter,drop table.'
end
The trigger is defined at the database level and is intended to prevent any create, alter and drop statements on any table. That means you cannot create a new table, alter or delete existing tables on the database. This is generally used by DBAs to lock the database from any changes during maintenance & patching.
Related
I have a stored procedure to run after a set of tables, all belonging to the same schema [DATA_Countries], is dropped and then re-inserted.
The operation is performed by another application, which drops and recreates the target table, over which I have no control.
Since the table is dropped and recreated each time, I can not use triggers on each target table.
Is there a way to get a trigger for each time a table is inserted into a specific schema, to return the name of such table and launch a parametrized stored procedure?
Thanks!
Yes, You can create DDL Triggers on SQL Server to track the DDL Changes. For example, If I want to track the changes in Stored Procedures on my Database AdventureWorks, I can create a trigger like this
CREATE TRIGGER td_ProcTrack
ON AdventureWorks
FOR CREATE_PROCEDURE, ALTER_PROCEDURE, DROP_PROCEDURE
AS
BEGIN
<my code>
END
Refer this Article for more detailed examples
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
I am new to triggers and cursors and would like to understand what a particular trigger is doing. Here is the Trigger.
CREATE TRIGGER [dbo].[trg_XOnUpdate]
ON TableX
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON
DECLARE #XID INT, #XKey NVARCHAR(33)
DECLARE updated_cursor CURSOR FOR
SELECT XID, XKey
FROM INSERTED
WHERE XStatus
IN ('AA', 'BB', 'CC')
OPEN updated_cursor
FETCH NEXT FROM updated_cursor INTO #XID, #XKey
WHILE ##FETCH_STATUS = 0
BEGIN
EXECUTE usp_UpdateXData #XID, #XKey
FETCH NEXT FROM updated_cursor INTO #XID, #XKey
END
CLOSE updated_cursor
DEALLOCATE updated_cursor
END
Understanding the Basic of Triggers
A trigger is an operation that is executed when some kind of event occurs to the database. It can be a data or object change. Listed below are the different types of tiggers:
Types of Triggers
DML(data manipulation language) triggers (SQL Server 2000- 80.0)
DDL(data definition language) triggers (SQL Server 2005- 90.0)
SQLCLR triggers (SQL Server 2005- 90.0)
Rules of Triggers
cannot create or modify Database objects using triggers
cannot perform any administrative tasks
cannot pass any kind of parameters
cannot directly call triggers
Advantage of Triggers
Triggers are useful for auditing data changes or auditing database as well as managing business rules. Below are some examples:
Triggers can be used to enforce referential integrity (For example you may not be able to apply foreign keys)
Can access both new values and old values in the database when going to do any insert, update or delete
Drill down further about triggers...
Understanding the Basic of Triggers
Understanding SQL Server inserted and deleted tables for DML triggers
I have a table were values can be altered by different users and records of 100k rows.
I made a stored procedure where in, it has a begin tran and at the last part
to either commit or rollback the changes depending on the situation.
So for now the problem we're encountering is a lock of that table. For example 1st user is executing the stored procedure thru the system, then the other users won't be able to select or also execute the stored procedure because the table is currently locked.
So is there anyway where I can avoid lock other than using dirty read. Or a way where I can rollback the changes made without using begin tran, because it is the main reason why the table is locked up.
Yes, you can at least (quick & dirty) enable SNAPSHOT isolation level for transactions. That will prevent locks inside the transactions.
ALTER DATABASE MyDatabase
SET ALLOW_SNAPSHOT_ISOLATION ON
ALTER DATABASE MyDatabase
SET READ_COMMITTED_SNAPSHOT ON
See for details.
Need lock for update a field in a table or maybe pop up a message alter user when this field is update. But still need do be insert or delete a record. i simply try to use command
DENY UPDATE ON JobEmp (Job) TO public
It will not let me do any thing to Job Column, can not add, change or delete. Need some help. Thanks
Using Code
CREATE TRIGGER tr_No_Update_Job
ON dbo.JobEmp
FOR UPDATE
AS
BEGIN
IF UPDATE(Job)
BEGIN
RAISERROR('This column cannot be updated', 16,1)
RETURN;
END
END
But when insert a new record, it also throw the error message. How can i only lock for update?
You can not Grant, Deny or Revok permission on one column of the table you can either deny UPDATE permission on a table on sql server permissions level or you need to create a Trigger to control column level permission.
Table Level Permissions
DENY UPDATE ON OBJECT::[Schema].[TableName] TO [PrincipalName];
Column Level Update Control
CREATE TRIGGER tr_No_Update_Job
ON dbo.JobEmp
FOR UPDATE
AS
BEGIN
IF UPDATE(Job)
BEGIN
RAISERROR('This column cannot be updated', 16,1)
RETURN;
END
END
Do the rollback from after update trigger:
create trigger trJobEmpUpd
on JobEmp
after update
as
if update(Job)
rollback
Have a look to BEGIN/COMMIT TRAN and transaction isolation levels.
If your questions is about Oracle
There is a syntax "for update" that locks a record (not a field)
https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:4530093713805
-> For SQL server I think the "for update" syntax is "Select ... WITH (updlock)..."
http://technet.microsoft.com/en-us/library/aa213026(v=sql.80).aspx
Note that as been noted by #huMpty duMpty you have to be in a transaction for the lock to be held...
This syntax will issue a row lock on the data selected, which will be released only on commit.
other users will be able to query the data (depends on the DBMS) but not to modify it.
I am pretty sure most other DBMS has the same / similar syntax for locking selected query results, while selecting the data - which allow atomicity - what you got from the "select" will be locked, in the same command, and no one else can intervene in the middle.
If you want to permanently not allow access to a column (for select or update) you should use a different scheme, and allow permisions on a view of the data , or only select permission with stored procedures for editing the actualy data.