SQL Update different columns based on value of one colum

Posted on 2014-03-27
Last Modified: 2014-03-27
I have a work table for our drivers routes that will show the selected route and any additional days that customer is serviced.  The route is created in a work table and then the additional service dates are updated with a query.  Using Access I could do it with this statement:
UPDATE (dbo_tblWrkRouteSheet INNER JOIN (dbo_ServiceSchedule INNER JOIN dbo_Service ON dbo_ServiceSchedule.ServiceUID = dbo_Service.ServiceUID) ON dbo_tblWrkRouteSheet.serviceid = dbo_Service.ServiceID) INNER JOIN dbo_Site ON (dbo_Site.ServiceLocation = dbo_Service.ServiceLocation) AND (dbo_tblWrkRouteSheet.siteid = dbo_Site.SiteID) SET dbo_tblWrkRouteSheet.monrte = IIf([dbo_Serviceschedule].[dayofweek]=1,'Mo',[monrte]), dbo_tblWrkRouteSheet.turte = IIf([dbo_Serviceschedule].[dayofweek]=2,'Tu',[turte]), dbo_tblWrkRouteSheet.wedrte = IIf([dbo_Serviceschedule].[dayofweek]=3,'We',[wedrte]), dbo_tblWrkRouteSheet.thurte = IIf([dbo_Serviceschedule].[dayofweek]=4,'Th',[thurte]), dbo_tblWrkRouteSheet.frirte = IIf([dbo_Serviceschedule].[dayofweek]=5,'Fr',[frirte]), dbo_tblWrkRouteSheet.satrte = IIf([dbo_Serviceschedule].[dayofweek]=6,'Sa',[satrte]), dbo_tblWrkRouteSheet.sunrte = IIf([dbo_Serviceschedule].[dayofweek]=7,'Su',[sunrte])
WHERE (((dbo_ServiceSchedule.EndDate) Is Null));

Open in new window

I'm now converting the program to VB and am trying to build the appropriate SQL statement and have been trying it in SQL Server 2012 Query Analyzer but I'm not getting the expected results.  With the following Query:
Select monrte, turte, wedrte, thurte,frirte from tblwrkroutesheet

If a customer is on a Monday/Thursday Route the result I should get is


But instead I'm getting


the table tblwrkroutesheet contains the details for one specific route/day and the table serviceschedule contains all the days of service so I want to update the tblwrkroutesheet table with the days that the customer is serviced.  What I'm really looking for that I can't find is something like:

update tblwrkroutesheet set
Select Case ServiceSchedule.dayofweek
      Case '1'   tblwrkroutesheet.monrte = 'mo'
      Case '2'   tblwrkroutesheet.turte = 'tu'
      Case '3'   tblwrkroutesheet.wedrte = 'we'
End Select

That way only one of the update statements are being processed.  I haven't found a way to do that and my current SQL code is:

update wrk set
wrk.monrte = case when sch.dayofweek = '1' then 'mo' else wrk.monrte end,
 wrk.turte = case when sch.dayofweek = '2' then 'tu' else  wrk.turte end,
 wrk.wedrte = case when sch.dayofweek = '3' then 'we' else  wrk.wedrte end,
 wrk.thurte = case when sch.dayofweek = '4' then 'th' else wrk.thurte end,
 wrk.frirte = case when sch.dayofweek = '5' then 'fr' else wrk.frirte end
 from tblwrkroutesheet wrk
inner join [twrscav].dbo.service sv on wrk.serviceid = sv.serviceid
inner join [twrscav].dbo.serviceschedule sch on sch.serviceuid = sv.serviceuid
inner join [twrscav] si on (sv.servicelocation = si.servicelocation) and (si.siteid = wrk.siteid)
 where sch.enddate is null

Open in new window

This code though seems to overwrite other days that may have already been updated.  Any idea's on how I can update different columns in tblWrkRouteSheet based on the value in serviceschedule.dayofweek????

By the way I will be running the Querey against datbases on SQL Server 2012 and SQL Server 2005 so it needs to work with both SQL versions
Question by:spaulissian
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
LVL 33

Expert Comment

ID: 39960059
Use this to get the correct set:

SELECT wrk.*
from tblwrkroutesheet wrk
inner join [twrscav].dbo.service sv on wrk.serviceid = sv.serviceid
inner join [twrscav].dbo.serviceschedule sch on sch.serviceuid = sv.serviceuid
inner join [twrscav] si on sv.servicelocation = si.servicelocation and si.siteid = wrk.siteid
 where sch.enddate is null

Open in new window


Author Comment

ID: 39960169
My issue deals with the update not the select.  That select statement returns all the values from the tblwrkroutesheet table as expected.  However, the particular columns monrte, turte, wedrte, thurte, ... etc did not get updated with the update statement as expected.  It only appears to reflect the last record read.  For example if there is a serviceschedule.dayofweek = '1' and a different serviceschedule.dayofweek = '4' that customer should have the monday and thursday columns updated in the tblwrkroutesheet table.  However, only one of the columns is being updated, generally the last one.

It may be possible that the first update has not been committed to the table when the second update runs.  Bottom line is I really want to update only one field at a time and not have a case for each field.
LVL 33

Expert Comment

ID: 39960265
Without the entire procedure it's hard to tell. But as long as you don't use some weird transaction nesting, it should use the correct values. Keep also in mind, that due to your JOINs, you may have multiple lines from tblwrkroutesheet. In this case you may need a sub-select in the SET clause instead of the JOINs.
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.


Author Comment

ID: 39960367
Here is a sample of data from the serviceschedule table:

Cust  - Route - DayofWeek
Albertson's  - FL1 - 1 (monday)
Albertson's  - FL3 - 4 (thurdsay)
Safeway - FL1 - 1
Raley's  - FL1 - 1
Raley's - FL1 - 2
Raley's - FL2 - 3
Raley's - FL1 - 4
Raley's - FL2 - 5

The Route is insignificant.  I just want the tblwrkRouteSheet to indicate they are serviced on other days as well.  So the Resulting tblWrkRouteSheet should look like this:

Customer -    Mon - Tue - Wed - Thu - Fri
Albertson's -  MO -      -             - TH -
Safeway      - MO -      -         -          -
Raley's         - MO - TU - WE - TH - FR

So I'm trying to update different columns in tblwrkroutesheet based on whatever the dayofweek is in table serviceschedule.

What I'm getting is:
Customer -    Mon - Tue - Wed - Thu - Fri
Albertson's -   -      -             - TH -
Safeway      - MO -      -         -          -
Raley's         -    -     -   -    - FR
LVL 69

Accepted Solution

Scott Pletcher earned 500 total points
ID: 39960370
Yes, the joins with the UPDATE would produce a result like that.

Please try code below.  I'm not sure of the significance of "siteid", but, aside from a mistake with it, I think the code below does what you want to do.

update wrk
    wrk.monrte = sch_combined.monrte,
    wrk.turte = sch_combined.turte,
    wrk.wedrte = sch_combined.wedrte,
    wrk.thurte = sch_combined.thurte,
    wrk.frirte = sch_combined.frirte
from tblwrkroutesheet wrk
inner join (
    select sv.serviceid, si.siteid,
        max(case when sch.dayofweek = '1' then 'mo' else '' end) AS monrte,
        max(case when sch.dayofweek = '2' then 'tu' else '' end) AS turte,
        max(case when sch.dayofweek = '3' then 'we' else '' end) AS wedrte,
        max(case when sch.dayofweek = '4' then 'th' else '' end) AS thurte,
        max(case when sch.dayofweek = '5' then 'fr' else '' end) AS frirte
    from [twrscav].dbo.service sv
    inner join [twrscav].dbo.serviceschedule sch on sch.serviceuid = sv.serviceuid
    inner join [twrscav] si on sv.servicelocation = si.servicelocation
    where sch.enddate is null
    group by
        sv.serviceid, si.siteid
) AS sch_combined ON
    sch_combined.serviceid = wrk.serviceid AND
    sch_combined.siteid = wrk.siteid

Author Comment

ID: 39960415
Thank you that is exactly what I needed.

Author Closing Comment

ID: 39960417
Exactly the solution I needed.

Featured Post

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question