I want to get the id of a user for a given email, or if the email doesn’t exist, I want it to return MAX(id)+1.
So for the example below, I want:
- For email ‘aaa@gmail.com’, I want it to return 1
- For email ‘kkk@gmail.com’, I want it to return 9
I made an attempt but I couldn’t make it work the way I want.
DECLARE @USERS TABLE (id int, name varchar(50), email varchar(50)); INSERT INTO @USERS(id, name, email) VALUES (1, 'john', 'aaa@gmail.com'), (2, 'nick', 'bbb@gmail.com'), (3, 'alex', 'ccc@gmail.com'), (4, 'liam', 'ddd@gmail.com'), (5, 'noah', 'eee@gmail.com'), (6, 'oliver', 'fff@gmail.com'), (7, 'james', 'ggg@gmail.com'), (8, 'rob', 'hhh@gmail.com'); SELECT CASE WHEN (ISNULL(id, 0) = 0) THEN id ELSE (MAX(id) + 1) FROM @USERS WHERE email = 'ccc@gmail.com';
Advertisement
Answer
Two sub-queries inside a coalesce
should do the job.
DECLARE @TestEmail VARCHAR(50) = 'aaa@gmail.com'; SELECT COALESCE((SELECT TOP 1 id FROM @USERS WHERE email = @TestEmail), (SELECT MAX(id) + 1 FROM @USERS), 1);
This will only work in a simple scenario when you don’t call this concurrently, and you make use of the returned ID before you would ever call this again. Otherwise you would need to perform some locking to ensure it works as expected.