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

What is the best way to perform query by ID or instead get all?

I have to do a query filter but I don’t want to repeat code. I would like to do it in one simple query, the simplest possible.

Technology

SQL Server v18

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

The Acceptance Criteria

Get by ID if the ID has a value (one single record in this case) OR IF ID = NULL then GET ALL

I’ve been trying with AND, ORs, IS NOT NULL, etc. But I would like to get the records in a simplest query.

Currently this is my query:

DECLARE @EventLogId int = null
SET @EventLogId = NULL

-- Insert statements for procedure here
SELECT 
    EL.EventLogId,
    EL.EventLogDateTime,
    EL.Username,
    EL.EventLogTypeId,
    EL.ActionTypeId,
    EL.ProfessionalId,
    EL.BioId,
    EL.[Message],
    EL.ExceptionMessage,
    EL.StackTrace,
    ELTypes.[Name] AS EventLogTypeName,
    ATypes.[Name] AS ActionTypeName
FROM 
    dbo.EventLog EL
INNER JOIN 
    EventLogType ELTypes ON ELTypes.Id = EL.EventLogTypeId
INNER JOIN 
    ActionTypes ATypes ON ATypes.ActionTypeId = EL.ActionTypeId
WHERE 
    EL.EventLogId = @EventLogId 
    AND NOT(EL.EventLogId IS NULL)

Thanks for the help!

>Solution :

Just another option … coalesce()

WHERE  EL.EventLogId = coalesce(@EventLogId,EL.EventLogId)
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