存储过程中的条件顺序

时间:2013-08-21 19:41:05

标签: sql sql-server tsql stored-procedures sql-server-2008-r2

例如,我有这个存储过程

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

现在在我的应用程序中我将如何执行此操作:例如,用户选中了checkBox1,然后上面的查询将为ORDER BY EmpID否则,如果选中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将被执行?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

如果您只有两个排序值,那么您可以使用已经提到的任何解决方案。如果有许多排序参数,那么您可以考虑动态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

答案 2 :(得分:1)

我建议根据您选中的复选框在您的应用中订购您的收藏。 E.g。

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