Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way in SQL Server to get a string from a group of strings based on some predicate?

I’m trying to retrieve the status for a multi-step process which is stored in a sql server db. Each step is a record in a table.

When a client wants to know the status of that process, I would like to retrieve the statusses for all steps and have my query return a status of

  • ‘queued’ when all steps have status ‘queued’,
  • ‘in-progress’ when one of the steps has status ‘in-progress’,
  • ‘finished’ when all of the steps have status ‘finished’.

What would this query look like?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m not that experienced in Sql yet so I haven’t tried anything yet because I wouldn’t know where to start and can’t really find anything like this problem on Google.

Edit based on comment:
Tables look like:

Process
- id uniqueidentifier not null pk
- other stuff
Step
- id uniqueidentifier not null pk
- processId uniqueidentifier not null fk with process.id
- status nvarchar(30) not null

So some sample data for step would be:

id processId status
ed9d1f80-1941-495a-a282-833fddf41174 6f940376-27b5-4899-8cf0-beb89877da46 in-progress
2738a403-7ad4-4396-9b5c-c641bc01f96f 6f940376-27b5-4899-8cf0-beb89877da46 queued
4e6a0c8e-49e9-4dc6-adbe-a74f27aff36f 6f940376-27b5-4899-8cf0-beb89877da46 queued

which should result in my query returning:

processId status
6f940376-27b5-4899-8cf0-beb89877da46 in-progress

>Solution :

You can check using the following query:

DECLARE @pid int = 7; --whatever the ID of this process is.

SELECT 
   CASE 
   WHEN EXISTS (SELECT 1 FROM ProcessSteps WHERE ProcessID = @pid AND Status = 'in-progress') THEN 'in-progress'
   WHEN NOT EXISTS (SELECT 1 FROM ProcessSteps WHERE ProcessID = @pid AND Status = 'finished') THEN 'queued'
   ELSE 'finished'
   END AS ProcessStatus
FROM ProcessSteps
WHERE ProcessID = @pid

The query first checks if any of the steps are in-progress. If there is any, the status of in-progress is returned. Next is checks if all the steps are finished, and if not returned queued, otherwise it returns finished.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading