我写了以下存储过程。如果我不使用IF ELSE块,Order by子句工作正常但我需要使用IF ELSE来构建我的select语句。订购方式不适用于IF else块。你能告诉我我做错了什么吗? 在此先感谢!
ALTER PROCEDURE [dbo].[GetLookupItem]
-- #description Gets LookupItem
-- #tables Subscriber.Reference.LookupItem,Subscriber.Reference.LookupText,Subscriber.Reference.LookupType
-- #parameter: @LookupTypeId This parameter defines a type of lookup
-- #parameter: @LookupTextAbbreviationId This Variable decides to tie Lookup Text to Abbreviation or Full Text. Most of the cases Full text will be used.
-- #parameter: @LanguageCode To show the Lookup Text in this Language
@LookupTypeId int,
@LookupTextAbbreviationId int ,
@LanguageCode varchar(5)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @MonthType int
SET @MonthType = (SELECT Id FROM Subscriber.Reference.LookupType WHERE Name = 'Months')
IF @LookupTextAbbreviationId IS NULL
BEGIN
SELECT RLI.Id,RLT.Value
FROM Subscriber.Reference.LookupItem RLI
INNER JOIN Subscriber.Reference.LookupText RLT
ON RLI.LookupTextId = RLT.Id AND RLT.LanguageCode = @LanguageCode AND RLI.LookupTextAbbreviationId IS NULL -- LookupTextAbbreviationId will be null for full text records in Subscriber.Reference.LookupItem
WHERE RLI.LookupTypeId = @LookupTypeId
END
ELSE
SELECT RLI.Id,RLT.Value
FROM Subscriber.Reference.LookupItem RLI
INNER JOIN Subscriber.Reference.LookupText RLT
ON RLI.LookupTextAbbreviationId = RLT.Id AND RLT.LanguageCode = @LanguageCode
WHERE RLI.LookupTypeId = @LookupTypeId
ORDER BY -- Order by will change for only Months by ID
CASE @LookupTypeId
WHEN @MonthType THEN RLT.Id
END,
CASE
WHEN @LookupTypeId <> @MonthType THEN RLT.Value
END
IF (@@ERROR <> 0)
RETURN 1
ELSE
RETURN 0
END
答案 0 :(得分:0)
我认为你的order by子句语法混淆了 - 这个查询是否运行?还是会出现语法错误?
这是你在找什么?
ORDER BY -- Order by will change for only Months by ID
CASE @LookupTypeId
WHEN @MonthType THEN RLT.Id
ELSE RLT.Value
END
答案 1 :(得分:0)
当@LookupTypeId等于@MonthType时,是否要按RLT.Id进行订购,否则按RLT.Value进行订购?案件应该是这样的:
ORDER BY
CASE @LookupTypeId
WHEN @MonthType THEN RLT.Id
ELSE RLT.Value
END
但是,如果RLT.Id和RLT.Value不是同一类型,则会出现转换错误。如果RLT.Id为int且RLT.Value为varchar,那么您可以将大小写更改为:
ORDER BY
CASE @LookupTypeId
WHEN @MonthType THEN STR(RLT.Id)
ELSE RLT.Value
END