Reputation: 229
I have 3 values
I have 2 tables:
SecurityLevelDetails
SecurityUserDetails
I want to check the data whether it is already exists or not in SecurityUserDetails
. If exist, I want to retrieve that exist record, if not I want to retrieve record from SecurityLevelDetails
.
I try to make it as a single query, I can do using if condition. But I don't want to do.
I tried this. I know this is wrong.
Select
ReportHide, RColumnName, RFilterName
From
HQWebMatajer.dbo.SecurityLevelDetails sld
Where
SecurityLevel = 1
and not exists(select top 1
UserID, ReportHide, RColumnName, RFilterName
from
[HQWebMatajer].[dbo].[SecurityUserDetails]
where
[UserID] = 'faisal.3012'
and [ReportName] = 'TotalSales')
It's retrieving a record if it does not exist in SecurityUserDetails
. But I want to retrieve the record from SecurityUserDetails
if it exists
UPDATED I got the result from below code. But I am trying to make in single query
declare @flags int = 0;
select top 1 @flags=count(*)
from [HQWebMatajer].[dbo].[SecurityUserDetails]
where [UserID]='faisal.3012' and [ReportName]='TotalSales';
if(@flags>0)
BEGIN
select top 1 UserID,ReportHide,RColumnName,RFilterName
from [HQWebMatajer].[dbo].[SecurityUserDetails]
where [UserID]='faisal.3012' and [ReportName]='TotalSales'
END
ELSE
BEGIN
select SecurityLevel,ReportHide,RColumnName,RFilterName
From HQWebMatajer.dbo.SecurityLevelDetails sld
where SecurityLevel=1 and ReportName='TotalSales'
END
Upvotes: 0
Views: 522
Reputation: 19194
One way to approach this is with UNION ALL
You have both sides defined and a UNION ALL joins them up
I'll stick together all of the code you have posted so far:
select top 1 UserID,ReportHide,RColumnName,RFilterName
from [HQWebMatajer].[dbo].[SecurityUserDetails]
where [UserID]='faisal.3012' and [ReportName]='TotalSales'
UNION ALL
select SecurityLevel,ReportHide,RColumnName,RFilterName
From HQWebMatajer.dbo.SecurityLevelDetails sld
where SecurityLevel=1
and ReportName='TotalSales'
and not exists(select *
from
[HQWebMatajer].[dbo].[SecurityUserDetails]
where
[UserID] = 'faisal.3012'
and [ReportName] = 'TotalSales')
Upvotes: 1