Environment : SQL Server 2005
I have this type of request
SELECT *
FROM user
WHERE EXISTS(
SELECT *
FROM user_access
WHERE user_access.user_id = user.user_id
AND user_access.access IN ('HIGH_LEVEL','MEDIUM_LEVEL')
)
AND EXISTS(
SELECT *
FROM user_service
WHERE user_service.role ='Manager'
AND user.id_user = user_service.user_id
)
AND user.is_active ='True'
But in the result I'd also like to get the result from the subquery, so I though about something like
DECLARE @user_access TABLE(user_id int,access nvarchar(30))
DECLARE @user_service TABLE(user_id int,service_id int,role nvarchar(10))
SELECT * FROM user
WHERE EXISTS(
SELECT user_id,access INTO [@user_access]
FROM user_access
WHERE user_access.user_id = user.user_id
AND user_access.access IN ('HIGH_LEVEL','MEDIUM_LEVEL')
)
AND EXISTS(
SELECT user_id , service_id,role INTO @user_service
FROM user_service
WHERE user_service.role ='Manager'
AND user.id_user = user_service.user_id
)
AND user.is_active ='True'
SELECT * FROM @user_acess
select * from @user_service
But I get the following error :
"Incorrect syntax near the keyword 'INTO'."
Do you have any idea how I can do it without doing twice the subquery (I tried with a temp table, same error) ?
EDIT : I'm sorry for my fellow who tried to solve my problem, I forget one thing : I have 2 subquery. See the requests. I want :
- All the active user, with high or medium access and who are manager
- All the service in which these users are
- All the access of these users
A temp table or variable would appear to be the simplest solution. Stuff the results of the subquery into a temp table or variable and then execute two select statements at the end of your procedure.
Update given your expansion of the original question
The solution for two subqueries is essentially the same as with one except that instead of returning two resultsets, you return three. As before, you use a temp table/variable per subquery: