简体   繁体   中英

SQL UPDATE based on condition

We need to update a table with the users id (NBK). The table with NBK also has the user status (0 - 1) and only one user will have 1 at a time. The challenage is to #1 capture the active user #2 update the other table with the user NBK. I hope the code below just has a simple syntex error that I cannot find?

Dim nb As String
Dim NBK As String

nb = [Employees]![NBK] & "' WHERE "
nb = nb & " " & [Employees]![Status] = '1'
NBK = " Update tbl_DateTracking SET NBK = "
NBK = NBK & "'" & nb & "' WHERE "
NBK = NBK & "CaseId = '" & CaseId & "' AND OCC_Scenario = '" & OCC_Scenario & "' ;"

DoCmd.RunSQL nb
DoCmd.RunSQL NBK

Several pointers of note here:

  1. You should use parameterized queries instead of string concatenation. This prevents/contains SQL injections and other issues regarding malformed input.
  2. Ideally, you should normalize the database so that "active user" is not a field on the user table. What happens when there are two users set as "active" in the database?

With this given schema however, you're going to want to use a sub-select query. Ex:

UPDATE tbl_DateTracking SET NBK=(SELECT NBK FROM Employees WHERE Status=1 LIMIT 1) WHERE CaseID=? AND OOC_Scenario=? and then pass in CaseId and OOC_Scenario as the parameters.

Note, I'm not familiar with VB or how it interacts with SQL; The above is just an example, you'll have to apply it to your application and alter it to make it work. The way you're building and running the nested queries also looks like it won't work, since your first query doesn't contain a command (You probably want SELECT , I think . Does VB do that automatically with []![] syntax?), and when you nest it inside the second query, it's not surrounded with () . Running the first query by itself also has no effect if you're including it as a sub-query in the second one.

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