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
  • 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.
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)


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

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
SQL Help 27 45
Query Syntax 17 34
Passing Parameter to Stored Procedure 4 24
How to resolve SQL Server DB deadlock which makes my application hangs ? 6 27
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

773 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