我需要一个可以在标志上动态基于的查询和/或子句。我正在使用SQL Server2014。
考虑以下示例:
declare @UGFlag char(1)
declare @PGFlag char(1)
declare @DoctrateFlag char(1)
create table #FiltQual(Candidate_ID int) -- Final Output
create table #FiltUG(Candidate_ID int)
create table #FiltPG(Candidate_ID int)
create table #FiltDOC(Candidate_ID int)
insert into #FiltUG
select '1' union
select '2' union
select '3'
insert into #FiltPG
select '1' union
select '2'
insert into #FiltPG
select '2' union
select '3' union
select '4' union
select '5'
--Case 1
set @UGFlag='Y'
set @PGFlag='Y'
set @DoctrateFlag = 'Y'
--Desired Output
Candidate_ID
2
Case 2
set @UGFlag='N'
set @PGFlag='N'
set @DoctrateFlag = 'N'
Desired Output
Candidate_ID
1
2
3
4
5
Case 3:
set @UGFlag='N'
set @PGFlag='Y'
set @DoctrateFlag = 'N'
Desired Output
Candidate_ID
1
2
Case 4:
set @UGFlag='Y'
set @PGFlag='Y'
set @DoctrateFlag = 'N'
Desired Output
Candidate_ID
1
2
我想将数据填充到trhee标志上的#FiltQual
基础中。旗帜可以包含" y"或" n",如果是'y',则应使用"'y",并且应该应用"'y"或"应应用"或"。
类似的东西应该有效:
SELECT COALESCE(UG.Candidate_ID, PG.Candidate_ID, DOC.Candidate_ID) AS Candidate_ID
FROM #FiltUG AS UG
FULL OUTER JOIN #FiltPG AS PG ON UG.Candidate_ID = PG.Candidate_ID
FULL OUTER JOIN #FiltDOC AS DOC ON PG.Candidate_ID = DOC.Candidate_ID
WHERE ((@UGFlag='Y' AND UG.Candidate_ID IS NOT NULL) OR (@UGFlag='N'))
AND
((@PGFlag='Y' AND PG.Candidate_ID IS NOT NULL) OR (@PGFlag='N'))
AND
((@DoctrateFlag='Y' AND DOC.Candidate_ID IS NOT NULL) OR (@DoctrateFlag='N'))
关键想法是在所有表之间使用FULL JOIN
。然后使用,例如:
(@UGFlag='Y' AND UG.Candidate_ID IS NOT NULL) OR (@UGFlag='N')
如果相应的表滤波器(@UGFlag
(等于'Y
,则将NOT NULL
条件应用于表(#FiltUG
(。
演示此处
不是一个完整的答案,但是以下抽象模式可以起作用。您要做的就是用实际检查堆放状态指示器的检查。
SELECT *
FROM Table
WHERE (@ConditionIndicator = 'Y' AND (Column = @Value))
一个更具体的示例,无法解决您的示例数据:
DECLARE @Filter NCHAR(1);
SET @Filter = 'Y'; -- Change to 'N' (or anything other than 'Y') to see the results change
SELECT *
FROM sysobjects
WHERE (@Filter = 'Y' AND name = 'sysrscols')
当@filter =='y'时,它返回1行。当@filter是" Y"以外的其他任何东西时,它不会返回行。
希望这会有所帮助。
编辑以添加:
对不起,只需重新阅读您的问题即可。您需要以下更类似于下面的东西,但是它有效地使用了相同的模式:
DECLARE @Filter NCHAR(1);
SET @Filter = 'Y';
SELECT *
FROM sysobjects
WHERE (@Filter = 'Y' AND (name = 'sysrscols' AND xtype = 'S'))
OR (@Filter != 'Y' AND (name = 'sysrscols' OR xtype = 'S'))