我试图在存储过程中使用IF THEN循环,如下所示:
@A varchar(100),
@B varchar(100)
AS
BEGIN
IF (@A = 'NULL' AND @B = 'NULL')
BEGIN
SELECT TOP 5 X1, X2, A, B, Y1, Y2, X3
FROM mytable
ORDER BY Y1 DESC
SELECT TOP 5 X1, X2, A, B, Y1, Y2, X3
FROM mytable
ORDER BY Y2 DESC
END
ELSE IF (@A = 'NULL' AND @B IS NOT NULL)
BEGIN
SELECT TOP 5 Y1Rank, X1, X2, A, B, Y1, Y2, X3
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY B ORDER BY Y1 DESC) AS 'Y1Rank'
FROM mytable
WHERE B = @B
) b1
SELECT TOP 5 Y2Rank, X1, X2, A, B, Y1, Y2, X3
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY B ORDER BY Y2 DESC) AS 'Y2Rank'
FROM mytable
WHERE B = @B
) b2
END
ELSE IF (@A IS NOT NULL AND @B = 'NULL')
BEGIN
SELECT TOP 5 Y1Rank, X1, X2, A, B, Y1, Y2, X3
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY A ORDER BY Y1 DESC) AS 'Y1Rank'
FROM mytable
WHERE A = @A
) b3
SELECT TOP 5 Y2Rank, X1, X2, A, B, Y1, Y2, X3
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY A ORDER BY Y2 DESC) AS 'Y2Rank'
FROM mytable
WHERE A = @A
) b4
END
ELSE
BEGIN
SELECT TOP 5 Y1Rank, X1, X2, A, B, Y1, Y2, X3
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY A, B ORDER BY Y1 DESC) AS 'Y1Rank'
FROM mytable
WHERE A = @A AND B = @B
) b5
SELECT TOP 5 Y2Rank, X1, X2, A, B, Y1, Y2, X3
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY A, B ORDER BY Y2 DESC) AS 'Y2Rank'
FROM mytable
WHERE A = @A AND B = @B
) b6
END
END
GO
有没有人可以帮我这个? 非常感谢。
=============================================== ============================================ 顺便说一句,我尝试在查询中使用相同的代码但不是存储过程。 我试过了
DECLARE @A varchar(100),
@B varchar(100)
SET @A = 'NULL'
SET @B = 'Bravo'
和
DECLARE @A varchar(100),
@B varchar(100)
SET @A = 'Alpha'
SET @B = 'NULL'
然后跟着我在存储过程中使用的代码完全相同,它正是我想要的!我认为它们应该是等价的,但不知何故只能在普通查询中工作,而不能在存储过程中工作......我真的很困惑。
答案 0 :(得分:0)
尝试使用参数的默认值,如下所示:
@A varchar(100) = 'NULL',
@B varchar(100) = 'NULL'
这样,如果用户只提供一个参数的值,则另一个参数只使用默认值。
答案 1 :(得分:0)
declare @a as varchar(10)=NULL
if @a is null
SELECT @a as [a]
declare @b as varchar(10)='NULL'
if @b is null
SELECT @b as [b]
尝试上面的代码is null
和='NULL'
不是一回事,你似乎已混合并匹配它们。