我的问题
我正在尝试在查询中执行MERGE
查询,以便将结果从一个表中提取到另一个表中。这一切都很好,除了一点点小问题......
为从表中获取数据而执行的查询取决于名为 的变量@User_ID
。
如果@User_ID
是NULL
则执行子查询A,否则执行子查询B。
我遇到的问题是我不知道如何IF
在子查询中放置...我该怎么做?
我尝试过的...
这是我到目前为止所拥有的:
请注意,这可能有效,但由于我运行的是 SQL Server 2008 而不是 2012(我认为),所以我认为该IIF
功能不可用,所以我需要另一种方法来实现这一点。
-- Get the relevant logins for the past 12 weeks and insert
-- them into the temporary table where the week number is the same
MERGE INTO #Number_Of_Logins AS NOL
USING (
SELECT IIF (ISNULL(@User_ID,0), (
SELECT
Year(UA.Audit_When) AS Year_Num,
DatePart(wk, UA.Audit_When) AS Week_Number,
Count(*) AS Num_Logins
FROM User_Auditing UA
WHERE Audit_Type = 'SYSLI'
AND User_ID = @User_ID
AND DATEDIFF(wk, Audit_When, GETDATE()) <= 11
GROUP BY Year(Audit_When), DatePart(wk, Audit_When)
),
(
SELECT
Year(UA.Audit_When) AS Year_Num,
DatePart(wk, UA.Audit_When) AS Week_Number,
Count(*) AS Num_Logins
FROM User_Auditing UA
JOIN User_Profiles UP ON UA.User_ID = UP.User_ID
WHERE UA.Audit_Type = 'SYSLI'
AND UP.Company_ID = @Company_ID
AND DATEDIFF(wk, UA.Audit_When, GETDATE()) <= 11
GROUP BY Year(Audit_When), DatePart(wk, UA.Audit_When)
)
)
) AS TEST
ON NOL.Week_Number = TEST.Week_Number
WHEN MATCHED THEN
UPDATE
SET Number_Of_Logins = Num_Logins;
更新
我也尝试过使用CASE
,我收到以下错误:
在预期条件的上下文中指定的非布尔类型的表达式,靠近“THEN”。