DECLARE @startIndex INT, --用来判断的变量
@ordertype NVARCHAR(500), --条件语句
@SqlBase NVARCHAR(500) --最终的sql语句
SELECT @startIndex=3
SELECT @ordertype=CASE --根据条件组合sql语句
WHEN @startIndex=1 THEN
'ORDER BY CM.GeneralID DESC '
WHEN @startIndex=2 THEN
'ORDER BY CM.GeneralID ASC '
WHEN @startIndex=3 THEN
'ORDER BY CM.DefaultPicUrl DESC '
END
--拼凑最终的sql语句
SELECT @SqlBase='SELECT TOP 1 GeneralID FROM PE_CommonModel CM WHERE ISNULL(CM.DefaultPicUrl , '''')!='''' '+'and CM.NodeID IN('''+CAST(34 AS NVARCHAR(10))+''')'+@ordertype
SELECT @SqlBase --查看sql语句
EXEC (@SqlBase) --执行sql语句