接受订单的存储过程&按列排序作为参数,然后排序表

时间:2016-09-22 06:13:30

标签: sql-server

我试图通过作为参数传递order和order来对sql表进行排序,同样适用于列类型datetime但是对于string和int类型,它给出了默认的排序数据。下面是我的存储过程

 CREATE PROCEDURE [dbo].[sp_SearchCity]
    -- Add the parameters for the stored procedure here
    @cityname varchar(50),
    @orderby varchar(50),
    @order varchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    if(@order = 'asc')
    begin
        SELECT id,city,status,CONVERT(VARCHAR(11),modifiedDatetime,6) as Date from cityMaster where city like '%'+@cityname+'%' order by case when @orderby = 'city' then city End,
case when @orderby='status' then status end,
case when @orderby='modifiedDatetime' then modifiedDatetime end asc
    end
    else if(@order ='desc')
    begin
        SELECT id,city,status,CONVERT(VARCHAR(11),modifiedDatetime,6) as Date from cityMaster where city like '%'+@cityname+'%' order by case when @orderby = 'city' then city End,
case when @orderby='status' then status end,
case when @orderby='modifiedDatetime' then modifiedDatetime end desc
    end



END


GO

请帮助

2 个答案:

答案 0 :(得分:0)

更改您的@Order IF Else,如下所示:

对于升序订单,postfix asc是可选的,所以我没有输入代码

DECLARE @tblTemp AS Table(
    Id INT,
    Name VARCHAR(50),
    Status INT
)

if(@order = 'asc')
begin
        INSERT INTO @tblTemp
        SELECT id,city,status,CONVERT(VARCHAR(11),modifiedDatetime,6) as Date 
        from cityMaster where city like '%'+@cityname+'%' 
        order by 
            case when @orderby = 'city' then city End,
            case when @orderby='status' then status end,
            case when @orderby='modifiedDatetime' then modifiedDatetime end 
end
else if(@order ='desc')
begin
        INSERT INTO @tblTemp
        SELECT id,city,status,CONVERT(VARCHAR(11),modifiedDatetime,6) as Date 
        from cityMaster where city like '%'+@cityname+'%' 
        order by 
            case when @orderby = 'city' then city End desc,
            case when @orderby='status' then status end desc,
            case when @orderby='modifiedDatetime' then modifiedDatetime end desc
end

SELECT * FROM @tblTemp

答案 1 :(得分:0)

您可以使用动态SQL,如下所示:

char *options = "n:l:u:";