如何在 T-sql 中的 IF 中使用 select 语句
How to use select statements with in IF in T-sql
谁能帮我在 SQL 的 IF 语句中使用 select 的语法。当我在 IF 中使用 BEGIN 和 END 时出现错误。
ALTER PROCEDURE Proc1 @MonthSelection AS INT = 0
AS
BEGIN
IF (@MonthSelection = 0)
BEGIN
SELECT
YEAR([EventStartDate]) AS [Year]
,MONTH([EventStartDate]) AS [Month Number]
,DATENAME(MONTH,DateAdd( month ,MONTH([EventStartDate]), 0 ) - 1) AS [Month]
,COUNT([UserID]) AS [Total Number of Logins]
FROM [Table1]
WHERE eventtype ='login'
GROUP BY YEAR([EventStartDate])
,MONTH([EventStartDate])
ORDER BY YEAR([EventStartDate])
,MONTH([EventStartDate]
END
ELSE
BEGIN
SELECT
YEAR([EventStartDate]) AS [Year]
,MONTH([EventStartDate]) AS [Month Number]
,DATENAME(MONTH,DateAdd( month ,MONTH([EventStartDate]), 0 ) - 1) AS [Month]
,COUNT([UserID]) AS [Total Number of Logins]
FROM [Table1]
WHERE eventtype ='login'
AND MONTH([EventStartDate]) = @MonthSelection
GROUP BY YEAR([EventStartDate])
,MONTH([EventStartDate])
ORDER BY YEAR([EventStartDate])
,MONTH([EventStartDate]
END
END
我确实尝试过不使用 Begin 和 END ,但我仍然遇到错误。这段代码放在存储过程中。
您在 END
关键字之前缺少右括号。
这个:
...
ORDER BY YEAR([EventStartDate])
,MONTH([EventStartDate]
END
END
收件人:
...
ORDER BY YEAR([EventStartDate])
,MONTH([EventStartDate])
END
END
谁能帮我在 SQL 的 IF 语句中使用 select 的语法。当我在 IF 中使用 BEGIN 和 END 时出现错误。
ALTER PROCEDURE Proc1 @MonthSelection AS INT = 0
AS
BEGIN
IF (@MonthSelection = 0)
BEGIN
SELECT
YEAR([EventStartDate]) AS [Year]
,MONTH([EventStartDate]) AS [Month Number]
,DATENAME(MONTH,DateAdd( month ,MONTH([EventStartDate]), 0 ) - 1) AS [Month]
,COUNT([UserID]) AS [Total Number of Logins]
FROM [Table1]
WHERE eventtype ='login'
GROUP BY YEAR([EventStartDate])
,MONTH([EventStartDate])
ORDER BY YEAR([EventStartDate])
,MONTH([EventStartDate]
END
ELSE
BEGIN
SELECT
YEAR([EventStartDate]) AS [Year]
,MONTH([EventStartDate]) AS [Month Number]
,DATENAME(MONTH,DateAdd( month ,MONTH([EventStartDate]), 0 ) - 1) AS [Month]
,COUNT([UserID]) AS [Total Number of Logins]
FROM [Table1]
WHERE eventtype ='login'
AND MONTH([EventStartDate]) = @MonthSelection
GROUP BY YEAR([EventStartDate])
,MONTH([EventStartDate])
ORDER BY YEAR([EventStartDate])
,MONTH([EventStartDate]
END
END
我确实尝试过不使用 Begin 和 END ,但我仍然遇到错误。这段代码放在存储过程中。
您在 END
关键字之前缺少右括号。
这个:
...
ORDER BY YEAR([EventStartDate])
,MONTH([EventStartDate]
END
END
收件人:
...
ORDER BY YEAR([EventStartDate])
,MONTH([EventStartDate])
END
END