我在此SQL Server查询中使用IF语句时遇到问题。
我想要的是什么:
SELECT *
IF(ProgramId = NULL AND BranchId = NULL AND OrganizationId = NULL) {
--EXECUTE QUERY ONLY ON THIS CONDITION
}
ELSE IF(ProgramId = 68 AND BranchId = 78 AND OrganizationId = 2) {
--EXECUTE QUERY ONLY ON THIS CONDITION
}
ELSE {
--EXECUTE QUERY ONLY ON THIS CONDITION
}
FROM
[dbo].[UserMenu]
这是我的C#代码逻辑,请你把它转移到SQL
if (organization == null && program == null && branch == null)
{
/*retrieve usermenu table data*/
}
else if (organization == null && program == null && branch != null)
{
/*retrieve usermenu table data*/
}
else if (organization == null && program != null && branch != null)
{
/*retrieve usermenu table data*/
}
else if (organization == null && program != null && branch == null)
{
/*retrieve usermenu table data*/
}
else if (organization != null && program != null && branch != null)
{
/*retrieve usermenu table data*/
}
else if (organization != null && program == null && branch == null)
{
/*retrieve usermenu table data*/
}
else if (organization != null && program == null && branch != null)
{
/*retrieve usermenu table data*/
}
else if (organization != null && program != null && branch == null)
{
/*retrieve usermenu table data*/
}
请帮我解决一下。
感谢您的帮助
答案 0 :(得分:0)
如果我理解你的问题,你应该做这样的事情
Declare @Programid int,
Declare @BranchId int,
Declare @OrganizationId int
SELECT @Programid=ProgramId, @BranchId=BranchId,@OrganizationId = OrganizationId
FROM [dbo].[UserMenu]
IF (@ProgramId=NULL AND @BranchId=NULL AND @OrganizationId=NULL)
BEGIN
/* your if condition code goes here*/
END
ELSE IF(@ProgramId=68 AND @BranchId=78 AND @OrganizationId=2)
BEGIN
/* your else if condition code goes here*/
END
ELSE
BEGIN
/* your else condition code goes here*/
END
答案 1 :(得分:0)
我认为您希望按照这些条件对结果进行排序,如果有几个条件匹配,那么只需先选择匹配。如果是这样,你就可以这样做:
create table t(ID int, A int, B int)
insert into t values
(1, 1, 1),
(1, 1, null),
(1, null, null),
(2, 2, 1)
select ID, A, B from (select *,
row_number() over (partition by ID order by
case when A = 1 and B =1 then 1
when A = 1 and B is null then 2
when A is null and B is null then 3
else 4 end )as rn
from t
)t where rn = 1
输出:
ID A B
1 1 1
2 2 1
<强> EDIT1 强>
编辑问题后,我将问题理解为: 将变量传递给存储过程或您使用的任何内容:
Declare @ProgramID int,
Declare @BranchID int,
Declare @OrganizationID int
SELECT *
FROM [dbo].[UserMenu]
WHERE (ProgramID = @ProgramID OR @ProgramID IS NULL) AND
(BranchID = @BranchID OR @BranchID IS NULL) AND
(OrganizationID = @OrganizationID OR @OrganizationID IS NULL)