简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM