3

例如我有这个存储过程

Create Procedure sampleProcedure
AS
BEGIN 
Select EmpID, Name, Address, PhoneNumber From EmpTable
END

现在在我的应用程序中我将如何执行此操作:例如,用户检查了 checkBox1,然后上面的查询将是ORDER BY EmpIDelse 如果检查了 checkBox2,那么查询将是ORDER BY Name. 我必须创建两个程序吗?

Create Procedure sampleProcedure1
AS
BEGIN 
Select EmpID, Name, Address, PhoneNumber From EmpTable Order By EmpID
END
Create Procedure sampleProcedure2
AS
BEGIN 
Select EmpID, Name, Address, PhoneNumber From EmpTable Order By Name
END

如果 checkbox1 被选中,则 sampleProcedure1 将被执行,否则如果 checkbox2 被选中,则 sampleProcedure2 将被执行?

4

3 回答 3

4

为过程引入一个参数来指示排序顺序:

Create Procedure sampleProcedure1
  @orderByEmpId bit
AS
BEGIN 
  if (@orderByEmpId = 1)
    Select EmpID, Name, Address, PhoneNumber From EmpTable Order By EmpID
  else
    Select EmpID, Name, Address, PhoneNumber From EmpTable Order By Name
END

您可以将其进一步细化为:

CREATE PROCEDURE sampleProcedure1
  @orderByEmpId Bit
AS BEGIN 
  SELECT
    EmpID, Name, Address, PhoneNumber
  FROM EmpTable
  ORDER BY CASE WHEN @orderByEmpId = 1 THEN EmpID ELSE Name END
END
于 2013-08-21T19:43:42.227 回答
1

我建议根据您的复选框选择在您的应用程序中订购您的收藏。例如

if (checkbox1.Checked)
    employees = employees.OrderBy(x => x.EmpID).ToList();
else
    employees = employees.OrderBy(x => x.Name).ToList();

但是,如果您出于某种原因需要执行此 SQL 端,我建议使用参数化存储过程:

Create Procedure sampleProcedure1 
(
    @OrderByEmpID BIT = 1
)
AS
BEGIN 
    IF (@OrderByEmpID = 1)
        Select EmpID, Name, Address, PhoneNumber From EmpTable Order By EmpID
    ELSE
        Select EmpID, Name, Address, PhoneNumber From EmpTable Order By Name
END 
于 2013-08-21T19:46:52.733 回答
1

如果您只有两个排序值,那么您可以使用已经提到的任何解决方案。如果有很多排序参数,那么您可以为此考虑动态 SQL。

这是一个需要更多工作的快速而肮脏的示例……

CREATE PROCEDURE dbo.SortExamle
(
    @SortParam nvarchar(20)
)
AS
BEGIN
    DECLARE @SQL nvarchar(1000)
    SET @SQL = 'SELECT * FROM ICE_Users ORDER BY ' + @SortParam
    EXEC sp_executesql @SQL
END
于 2013-08-22T10:06:19.003 回答