是否可以将用户输入排序

时间:2014-09-22 00:32:01

标签: sql

是否可以使用SQL查询以及如何根据文本框中的用户输入进行排序,我要做的是从用户输入的日期获取表中的所有记录

SELECT  orderDate AS Date, orderPizzaTotals AS 'PIZZAS SOLD', 
        orderDrinkTotals AS 'DRINKS SOLD', 
        orderPriceTotal AS 'TRANSACTION TOTAL' 
FROM dbo.[Order] sort "USERINPUT.TEXT" 

2 个答案:

答案 0 :(得分:3)

如果在SQL Server中使用动态SQL,则可以根据动态信息(例如,从代码传递的参数)进行排序:

declare @userinput nvarchar(100) = 'your_column'

declare @sql nvarchar(1000) = N'SELECT  orderDate AS Date, 
    orderPizzaTotals AS ''PIZZAS SOLD'', 
    orderDrinkTotals AS ''DRINKS SOLD'', 
    orderPriceTotal AS ''TRANSACTION TOTAL'' FROM dbo.[Order] 
    ORDER BY ' + @userinput

exec sp_executesql @sql

答案 1 :(得分:0)

你可以用一个巨大的案例陈述来做到这一点:

SELECT  orderDate AS Date, orderPizzaTotals AS "PIZZAS SOLD", 
        orderDrinkTotals AS "DRINKS SOLD", 
        orderPriceTotal AS "TRANSACTION TOTAL"
FROM dbo.[Order] o
ORDER BY (case when USERINPUT.TEXT = 'Date' then Date end),
         (case when USERINPUT.TEXT = 'PIZZAS SOLD' then "PIZZAS SOLD" end),
         (case when USERINPUT.TEXT = 'DRINKS SOLD' then "DRINKS SOLD" end),
         (case when USERINPUT.TEXT = 'TRANSACTION TOTAL' then "TRANSACTION TOTAL" end)

使用单独的case语句的原因是为了处理列可能具有不同类型的事实。