I have a very large script which is creating multiple views. In a number of the views there is the same piece of script being used. This script is listed below.
CASE WHEN pc.[user_name] IN
(
SELECT [user_name]
FROM people AS p WITH(NOLOCK)
WHERE p.status_id = 1 p.last_login > DATEADD(MONTH, -12, GETDATE())
AND p.[user_name] NOT IN
(
SELECT p.[user_name]
FROM people AS p WITH(NOLOCK)
WHERE p.status_id IN (1,2) AND p.[user_name] LIKE '%2'
)
) THEN pc.[user_name]
ELSE 'standarduser' END AS created_by
Could someone point me in the right direction of how to write a function where I can pass in pc.[user_name] and it will return the correct value? I am new to functions in SQL. Thank you.
The function can be created as follows:
I have tried to simplify your select as much as possible based on the assumption that user_name is unique, i.e. a user_name cannot have both a status_ID of 1 and 2, this allowed me to remove a
NOT INfrom the statement, as you are first selecting a group of users where the status_ID is 1 then removing from them where the status_ID is 1 or 2 and the user name ends in 2. Since there will be be nobody in the first group who does not have a status_ID of 1, you can then just remove those in the first group whose username ends in 2, which doesn’t require a subquery, just a where clause.Having said all that, I would still be inclined to use a view or similar set based solution to achieve the same result. Something like: