Skip to content
Advertisement

Check if rows exists in SQL Server using R and then Insert or Update rows

I have a table with the below structure.

Clustered key is defined on columns Entity, UserName, UserRole.

UserStatus for an Entity-UserName-UserRole could be either Active or Inactive.

I could implement the INSERT and UPDATE statements for a dataframe df as follows:

Insert:

Update:

The code works fine but I would like it to check if for every row in the df for a combination of Entity-UserName-UserRole already exists in the TBL. If found, run the UPDATE statement else run the INSERT statement.

For example – SQL Server table data:

df to be inserted or updated:

What should happen:

Only rows 1st and 3rd should get ‘INSERTED‘ to the database TBL. UPDATE should only happen if the ‘UserStatus‘ changes for an existing Entity-UserName-UserRole Combination.

I guess I could run a ‘FOR’ loop for every row of the dataframe df but I think that would be slow and not an optimum solution.

Advertisement

Answer

You could create a temporary table (use # prefix in SQL Server) and send a MERGE query as suggested by @CharlieFace:

Not sure how ID is managed on the server : autonumber?

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement