Create after insert trigger that updates record in parent table after inserting record into child table - sql

I have two tables
License(licenseId, licenseNumber, lastUsed)
User(userId, userName, dateAdded, licenseId)
After adding a user to a respective license I would like to update the lastUsed field with the most recent date found within the user table using the license.
I am using MS Access

Since you are using Access 2010 you can create an After Insert Data Macro on the [User] table, something like this:

Related

How to insert into the table a user name record

I've a table. In this table I have two columns - 'insert_name' and 'modified_name'. I need to insert into this columns data about who has inserted data into the table('insert_name') and who has changed these data in the table (modified_name). How it can be done?
You are looking for basic DML statements.
If your record is already in the table, then you need to UPDATE it. Otherwise, when you are about to add your record to it and it doesn't already exist in the destination table then you are looking for INSERT INTO statement.
Example of updating information for record with first id:
UPDATE yourtable SET insert_name = 'value1', modified_name = 'value2' WHERE id = 1
Example of inserting new record:
INSERT INTO yourtable(id, company_name, product_name, insert_name)
VALUES (1, 'Google', 'PC', 'value1')
If you are looking for automatic changes to those columns then you need to look into triggers.
Remember that more often than not you may find that the application connecting to the database is using single database user in which case you probably know the context within the application itself (who inserts, who updates). This does eliminate triggers and put the task straight on simple insert/update commands from within your application layer.
You might be able to use the CURRENT_USER function to find the name of the user making the change.
The value from this function could then be used to update the appropriate column. This update could be done as part of the INSERT or UPDATE statement. Alternatively use an INSERT or UPDATE trigger.
Personally I avoid triggers if I can.
For those 2 columns add Current_User as Default constraint.
As the first time Insert Statement will save them with current login user names. For update write an Update trigger with the same Current_User statement for the column Modified_Name.
If and only if your application business logic can't update the column modified_nme then only go for Trigger.
See the use of Current_Use
https://msdn.microsoft.com/en-us/library/ms176050.aspx

Update SQL Server table with one time use values from another table

I have a table of users that has the usual suspects, name, email, etc. As the users complete an activity (queried from another table), I need to award them a gift card code.
update users
set giftcardcode = 'code from other table'
where email in (select email from useractivity where necessary conditions are met)
I have a table of unique gift card codes that are unique, one-time use codes. So I need to update my user table, setting the award code field equal to a distinct, unused gift card code from the gift card code table. Then I need to mark the 'used' field in the gift card table to 'Y'.
The goal is to do this with SQL and not any programming. I'm stumped.
I think there is a Many To Many relationship between User table and Activity table.
So, you can use a trigger to execute a query when update.
Each time a row will be updated in the Activity table, the trigger will do something.
It will UPDATE the User table by adding a new gift code.
I think you can add an attribute in your GiftCode table to easily check if the code as already been used. An you can get an unused code like that :
// Retrieve an unused code based on a BIT attribute.
SELECT TOP 1 [Code] FROM [GiftCode] WHERE IS_UNUSED = 1;
Don't forget to update this Gift code after using it.
You can use a SELECT statement including a sub SELECT statement to get a code too :
// Retrieve an unused code based on User table used codes.
SELECT TOP 1 [Code] FROM [GiftCode] WHERE [Code] NOT IN (SELECT [Code] FROM [User]);
It works well if you don't have too much users.
Otherwise , the first statement will be more efficient.
Don't forget to update the User table.
Now you can easily use one of these previous statement in a UPDATE statement.
It will be something like that :
UPDATE [User] SET [Code] = (
SELECT TOP 1 [Code] FROM [GiftCode] WHERE [Code] NOT IN (
SELECT [Code] FROM [User]))
WHERE USER_ID = // ...;
You can perform this in a trigger.
You can use a stored procedure, it's more efficient and will wrap all the SQL code in a compiled function. Then you can call it in your trigger.
You can execute a stored procedure in a job (see SQL Server Agent jobs) too.
create a Trigger on your table for update and do what you want inside it using inserted and deleted

Automatically create record when another is created

I have two tables in my database: Users, Roles and Membership. The Membership table assigns users to specific Roles.
How could I automatically create the Membership record for anytime a new record is inserted in Users.
Example: When a user is created and assigned an ID number (# 562), The database would automatically add them to the Membership table with a specific role ID.
How could I do this?
Write an AFTER INSERT TRIGGER on Users TABLE, that will INSERT the new Row in the Membership table.
http://msdn.microsoft.com/en-us/magazine/cc164047.aspx
Assuming you have a Default RoleID for your new Membership row, when a new User is inserted in Users table, something like this should work.
CREATE TRIGGER TRI_USERS_INSERT on Users
AFTER INSERT
AS
SET NOCOUNT ON
-- If you have a Default RoleID, select that into a variable and use it in the INSERT below.
-- For this example, I am using just the number 1
-- Also assumes that the ID for Memberships table is AUTO GENERATED, so it's not in INSERT list.
INSERT INTO Memberships (UserID, RoleID)
SELECT ID, 1 FROM INSERTED
GO

How to Create Trigger to Keep Track of Last Changed Data

CREATE TABLE Member
(
memberID - PK
memberName
dateRegistered - one time process
);
CREATE TABLE MemberLastChanged
(
memberID
memberName
dateEntered
);
If by any chance a user changes his member name, i need to keep track of the currently changed memberName in a history table.
For example, current info is:
memberID: 5534 memberName: james
User changes it to:
memberID: 5534 memberName:
mark
By now, "Member" will hold current values:
5534 and mark
AND
"MemberLastChanged" will hold:
5534 and james
How can i achieve this in t-sql using trigger?
CREATE TRIGGER TRG_Member_U ON Member FOR UPDATE
AS
SET NOCOUNT ON
INSERT MemberLastChanged (memberID, memberName)
SELECT
D.memberID, D.memberName
FROM
DELETED D JOIN INSERTED I ON D.memberID = I.memberID
WHERE
D.memberName <> I.memberName
GO
Also, add a default of GETDATE to dateRegistered so it's recorded automatically.
This also filters out dummy updates by comparing new and old values (INSERTED vs DELETED).
INSERTED and DELETED are special tables available only in trigger.
You create an UPDATE trigger - triggers have access to two logical tables that have an identical structure to the table they are defined on:
INSERTED, which is the new data to go into the table
DELETED, which is the old data the is in the table
See this MDSN article on using these logical tables.
With this data you can populate your history table.
CREATE TRIGGER trg_Member_MemberUpdate
ON dbo.Member AFTER UPDATE
AS
INSERT INTO dbo.MemberLastChanged(memberID, memberName)
SELECT d.MemberID, d.MemberName
FROM DELETED d
You want to have an AFTER UPDATE trigger on your users table - something like:
CREATE TRIGGER trg_MemberUpdated
ON dbo.Member AFTER UPDATE
AS BEGIN
IF UPDATE(memberName)
INSERT INTO
dbo.MemberLastChanged(memberID, memberName, dateEntered)
SELECT
d.MemberID, d.MemberName, GETDATE()
FROM
Deleted d
END
Basically, this trigger checks to see whether the memberName property was updated; if so, a row with the old values (which are available in the Deleted pseudo table inside the UPDATE trigger) is inserted into MemberLastChanged

Sql Server trigger insert values from new row into another table

I have a site using the asp.net membership schema. I'd like to set up a trigger on the aspnet_users table that inserted the user_id and the user_name of the new row into another table.
How do I go about getting the values from the last insert?
I can select by the last date_created but that seems smelly. Is there a better way?
try this for sql server
CREATE TRIGGER yourNewTrigger ON yourSourcetable
FOR INSERT
AS
INSERT INTO yourDestinationTable
(col1, col2 , col3, user_id, user_name)
SELECT
'a' , default , null, user_id, user_name
FROM inserted
go
You use an insert trigger - inside the trigger, inserted row items will be exposed as a logical table INSERTED, which has the same column layout as the table the trigger is defined on.
Delete triggers have access to a similar logical table called DELETED.
Update triggers have access to both an INSERTED table that contains the updated values and a DELETED table that contains the values to be updated.
You can use OLDand NEW in the trigger to access those values which had changed in that trigger. Mysql Ref
In a SQL Server trigger you have available two psdeuotables called inserted and deleted. These contain the old and new values of the record.
So within the trigger (you can look up the create trigger parts easily) you would do something like this:
Insert table2 (user_id, user_name)
select user_id, user_name from inserted i
left join table2 t on i.user_id = t.userid
where t.user_id is null
When writing triggers remember they act once on the whole batch of information, they do not process row-by-row. So account for multiple row inserts in your code.
When you are in the context of a trigger you have access to the logical table INSERTED which contains all the rows that have just been inserted to the table. You can build your insert to the other table based on a select from Inserted.
Create
trigger `[dbo].[mytrigger]` on `[dbo].[Patients]` after update , insert as
begin
--Sql logic
print 'Hello world'
end