SQLServer proc动态where条件

时间:2018-09-05 05:06:34

标签: sql-server

我想用动态where条件构造选择查询并将其插入到一个临时表中。

例如。

ALTER PROCEDURE asp_My_Proc 
(
    @empName nvarchar(50),
    @limit_Operator nvarchar(2), -- Possible values '>' or '<'
    @limit_Value   int
)

INSERT INTO #table1
    Select  c1,c2,c3 from Employee where empName  LIKE '%' + COALESCE(@empName, empName) + '%' and limit > 100

过程执行脚本:

EXECUTE asp_My_Proc 
   'John'
  , '>'
  ,10

GO

Limit_value条件,我必须基于'limit_Operator'变量添加极限条件。如何动态构建它。

2 个答案:

答案 0 :(得分:1)

...
WHERE (@limit_Operator = '>' and t.limit > @limit_value)
   OR (@limit_Operator = '<' and t.limit < @limit_value)

答案 1 :(得分:0)

Dynamic sql仅是可能的,而这是避免sql injection的最佳方法

    CREATE TABLE #EMP (
EMPNO INT PRIMARY KEY,
ENAME VARCHAR(10),
JOB VARCHAR(9),
MGR INT NULL,
HIREDATE DATETIME,
SAL NUMERIC(7,2),
COMM NUMERIC(7,2) NULL,
DEPT INT)

INSERT INTO #EMP VALUES
    (1,'JOHNSON','ADMIN',6,'12-17-1990',18000,NULL,4)
INSERT INTO #EMP VALUES
    (2,'HARDING','MANAGER',9,'02-02-1998',52000,300,3)
INSERT INTO #EMP VALUES
    (3,'TAFT','SALES I',2,'01-02-1996',25000,500,3)
INSERT INTO #EMP VALUES
    (4,'HOOVER','SALES I',2,'04-02-1990',27000,NULL,3)
INSERT INTO #EMP VALUES
    (5,'LINCOLN','TECH',6,'06-23-1994',22500,1400,4)
INSERT INTO #EMP VALUES
    (6,'GARFIELD','MANAGER',9,'05-01-1993',54000,NULL,4)
INSERT INTO #EMP VALUES
    (7,'POLK','TECH',6,'09-22-1997',25000,NULL,4)
DECLARE 
    @EMPNAME NVARCHAR(50)='JOH',
    @LIMIT_OPERATOR NVARCHAR(2)='>', -- POSSIBLE VALUES '>' OR '<'
    @LIMIT_VALUE   INT=100


DECLARE @A VARCHAR(MAX)
SET @A =CONCAT('
    SELECT  * FROM #EMP 
    WHERE ENAME  LIKE ''%'' + COALESCE(''',@EMPNAME,''', ENAME) + ''%'' AND SAL ',@LIMIT_OPERATOR,' ',@LIMIT_VALUE,'','')
    --EXEC (@A)
    SELECT @A