如何使用sp_executesql在动态sql中使用文本值作为变量



我有以下表格:

CREATE TABLE Wages (EmpID INT, Amount MONEY)
INSERT INTO Wages VALUES (1,25000), (2,30000), (3,35000), (4, 40000)
SELECT * FROM Wages

我想创建一个使用sp_executesql的过程,在那里我不仅可以改变where子句中的值,还可以改变关系——即大于(>)或小于(<)。

假设我有:

SELECT * FROM Wages WHERE EmpID > 2 AND Amount > 30000 

SELECT * FROM Wages WHERE EmpID <= 2 AND Amount <= 30000 

我该如何编码,以便我可以传入'<'或'='而不是'>来得到这个:

SELECT * FROM Wages WHERE EmpID < 2 AND Amount < 30000 

我试过了:

DECLARE @Amount MONEY
DECLARE @EmpID INT
DECLARE @EmpSYMBOL NVARCHAR(2)
DECLARE @AmountSYMBOL NVARCHAR(2) 
DECLARE @SQL2 NVARCHAR(2000) = 'SELECT * FROM Wages WHERE EmpID '+ @EmpSYMBOL+' @EmpID AND Amount '+ @AmountSYMBOL+' @Amount'
EXEC sp_executesql @SQL2, N'@EmpID INT, @Amount MONEY,  @EmpSYMBOL NVARCHAR(2), @AmountSYMBOL NVARCHAR(2)',2, 30000,'<','<';

但是,尽管它运行没有错误,没有返回

返回一个错误:

DECLARE @Amount MONEY
DECLARE @EmpID INT
DECLARE @EmpSYMBOL NVARCHAR(2)
DECLARE @AmountSYMBOL NVARCHAR(2) 
DECLARE @SQL2 NVARCHAR(2000) = 'SELECT * FROM Wages WHERE EmpID @EmpSYMBOL @EmpID AND Amount @AmountSYMBOL @Amount'
EXEC sp_executesql @SQL2, N'@EmpID INT, @Amount MONEY, @EmpSYMBOL NVARCHAR(2), @AmountSYMBOL NVARCHAR(2)',2, 30000,'<','<';

编辑鉴于下面的有用答案,我做了以下事情:

CREATE PROC GetWages  @EmpSYMBOL NVARCHAR(2), @EmpID INT,@AmountSYMBOL NVARCHAR(2), @Amount MONEY 
AS 
IF @EmpID IN (1,2,3,4) 
AND (@Amount BETWEEN 25000 AND 40000)
AND @EmpSYMBOL IN('>','<','<>','!=','=', '<=','>=') 
AND @AmountSYMBOL IN('>','<','<>','!=','=', '<=','>=')
BEGIN
DECLARE @SQL NVARCHAR(200)='
SELECT * FROM Wages WHERE Amount '+@AmountSYMBOL+' @Amount AND EmpiD '+@EmpSYMBOL+' @EmpID'
EXEC sp_executesql @SQl , N'@Amount MONEY ,@EmpID INT',@Amount, @EmpID
END
ELSE 
PRINT 'Input variable(s) out of range'

考虑到我正在做我自己的输入值参数检查,我想我也可以这样做:

ALTER PROC GetWages  @EmpSYMBOL NVARCHAR(2), @EmpID INT,@AmountSYMBOL NVARCHAR(2), @Amount MONEY 
AS 
IF @EmpID IN (1,2,3,4) 
AND (@Amount BETWEEN 25000 AND 40000)
AND @EmpSYMBOL IN('>','<','<>','!=','=', '<=','>=') 
AND @AmountSYMBOL IN('>','<','<>','!=','=', '<=','>=')
BEGIN
DECLARE @SQL NVARCHAR(200)='
SELECT * FROM Wages WHERE Amount '+@AmountSYMBOL
+' '+CAST(@Amount AS NVARCHAR(8))+' AND EmpiD '
+@EmpSYMBOL+' '+CAST(@EmpID AS NVARCHAR(1))
EXEC sp_executesql @SQl 
END
ELSE 
PRINT 'Input variable(s) out of range'

试试这样.....

DECLARE @Amount       MONEY
      , @EmpID        INT
      , @EmpSYMBOL    NVARCHAR(2) = '<'
      , @AmountSYMBOL NVARCHAR(2) = '<'
      , @SQL2         NVARCHAR(MAX);
  SET @SQL2 = N' SELECT * FROM Wages '
            + N' WHERE EmpID ' + @EmpSYMBOL + ' @EmpID 
                 AND Amount ' + @AmountSYMBOL + ' @Amount'
EXEC sp_executesql @SQL2
                 , N'@EmpID INT, @Amount MONEY'
                 , @EmpID = 2
                 , @Amount =30000

重要提示

没有安全的方法接受比较操作符作为参数而不经历很多麻烦。上面的示例容易出现sql注入。

相关内容

  • 没有找到相关文章

最新更新