如何在Exec存储过程中使用Where子句

时间:2016-03-10 09:37:04

标签: sql-server stored-procedures where-clause

我有一个存储过程

表格结构:

CREATE TABLE employee(
    id          INTEGER NOT NULL PRIMARY KEY,
    first_name  VARCHAR(10),
    last_name   VARCHAR(10),
    salary      DECIMAL(10,2),
    city        VARCHAR(20),   
)

向员工添加一些数据表:

INSERT INTO employee VALUES (1, 'Karvendhan',  'Palani',4789,'Agra');
GO

INSERT INTO employee VALUES (2, 'Bala',  'Manigandan',8789,'Bombay');
GO

INSERT INTO employee VALUES (3, 'Raj' ,  'Kishore',   5567,'London');
GO

INSERT INTO employee VALUES (4, 'Prayag',  'Pavithran',  4467,'Bombay');
GO

INSERT INTO employee VALUES (5, 'Selva',  'Kumar',  3456, 'Bombay');
GO

select * from employee;

我的存储过程:

CREATE PROCEDURE GetEmployeeBasedOnCity
(
    @city VARCHAR(20)
)

AS
BEGIN
    select * from employee where city = @city
END;

我正在执行存储过程:exec GetEmployeeBasedOnCity 'Bombay';

我收到了输出:

id      first_name       last_name        salary          city
-----------------------------------------------------------------
2       Bala             Manigandan       8789.00        Bombay
4       Prayag           Pavithran        4467.00        Bombay
5       Selva            Kumar            3456.00        Bombay

我需要在exec GetEmployeeBasedOnCity 'Bombay';时加上where子句 不在存储过程中。请帮助我...

  

想象一下查询(粗略期望)

     

exec GetEmployeeBasedOnCity 'Bombay' WHERE salary >5000

1 个答案:

答案 0 :(得分:5)

您最好的方法是独立于存储过程执行所需的查询。但是,如果必须在不进行更改的情况下使用现有存储过程,则可以将proc结果插入临时表中,然后在该表上应用其他过滤器:

CREATE TABLE #employee(
    id          INTEGER NOT NULL PRIMARY KEY,
    first_name  VARCHAR(10),
    last_name   VARCHAR(10),
    salary      DECIMAL(10,2),
    city        VARCHAR(20),   
);

INSERT INTO #employee
    EXEC GetEmployeeBasedOnCity 'Bombay';

SELECT *
FROM #employee
WHERE salary > 5000;