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.
Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.


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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
sql server query 12 25
MS SQL Delete Duplicate Rows Only 2 16
ASP.NET/VB: Convert Date and Time to YYYY-MM-DDTHH:MM:SS 3 10
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
I have a large data set and a SSIS package. How can I load this file in multi threading?
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.

856 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