我正在Microsoft SQL Server中尝试执行以下操作:
DECLARE @isparent int;
SET @isparent = iif(account.parentid is not null,
1,
0);
SELECT
IIF(@isparent = 1,
parentenrollment,
enrollment) "Enrollment"
FROM
Accounts
显然,这被大大简化了,但是其思想是将一个基于表中内容的值存储在变量中(@isparent,上方),然后稍后重新读取该变量,从而确定要显示的值。
这可能吗?如果可以,怎么办?
答案 0 :(得分:1)
根据您的代码,您不需要该变量,我认为您正在尝试这样做
SELECT
IIF(parentid is not null,
parentenrollment,
enrollment) Enrollment
FROM
Accounts
与
相同SELECT CASE WHEN ParentId IS NOT NULL THEN ParentEnrollment
ELSE Enrollment
END Enrollment
FROM Accounts
如果您真的想检查parentid
是否为空并将值存储在变量中,则您的查询应返回一(1)行,可以用两种方法完成
TOP和ORDER BY
SELECT TOP 1 @isparent = IIF(parentid IS NOT NULL, 1, 0)
FROM Accounts
ORDER BY <Your Order Here>
WHERE子句,其条件仅返回1行
SELECT @isparent = IIF(parentid IS NOT NULL, 1, 0)
FROM Accounts
WHERE <Type Your Condition(s) Here>
答案 1 :(得分:0)
您可以使用:
DECLARE @isparent int;
SELECT @isparent = IIF(parentid is not null, parentenrollment, enrollment)
FROM Accounts
WHERE ... -- condition that returns single row