存储过程中不正确的语法错误

时间:2019-03-11 10:17:48

标签: sql sql-server stored-procedures

我正在尝试在表单上实现搜索功能。过程接受搜索内容作为搜索参数

--[dbo].[sps_selectemployeedetails] 1,10,'aaa' alter PROCEDURE [dbo].[sps_selectemployeedetails] @page INT,@size INT,@search varchar(max)=null  AS BEGIN
    declare @totalrow int
    DECLARE @offset INT
    DECLARE @newsize INT
    DECLARE @sql NVARCHAR(MAX)
        IF(@page=0)
      BEGIN
        SET @offset = @page
        SET @newsize = @size
       END
       IF(@page=1)
      BEGIN
        SET @offset = @page
        SET @newsize = @size-1
       END
    ELSE 
      BEGIN
        SET @page = @page - 1
        SET @offset = @page*@size 

        SET @newsize = @size-1
      END
    SET NOCOUNT ON  if(@search is null)      begin   SET @sql = '
     WITH OrderedSet AS
    (
      SELECT *, ROW_NUMBER() OVER (ORDER BY EmpID) AS ''Index''
      FROM tbl_employeeDetails  
    )    SELECT * FROM OrderedSet WHERE [Index] BETWEEN ' + CONVERT(NVARCHAR(12), @offset) + ' AND ' + CONVERT(NVARCHAR(12), (@offset + @newsize))      end     else    begin   SET @sql = '
     WITH OrderedSet AS
    (
      SELECT *, ROW_NUMBER() OVER (ORDER BY EmpID) AS ''Index''
      from tbl_employeeDetails e,tbl_EmpAdddress a where e.FirstName LIKE ''%''' + CONVERT(NVARCHAR(12), @search) + '''%''  and a.EmpID=e.EmpID
    )    SELECT * FROM OrderedSet WHERE [Index] BETWEEN ' + CONVERT(NVARCHAR(12), @offset) + ' AND ' + CONVERT(NVARCHAR(12), (@offset + @newsize))  end
        EXECUTE (@sql)    END

我收到一个错误,说“ aaa”附近的语法不正确

2 个答案:

答案 0 :(得分:1)

使用sp_executesql并传入参数。代码看起来像这样:

@sql = '
WITH OrderedSet AS (
      SELECT *, ROW_NUMBER() OVER (ORDER BY EmpID) AS ''Index''
      FROM tbl_employeeDetails  
     )
SELECT *
FROM OrderedSet
WHERE [Index] BETWEEN @offset AND (@offset + @newsize)
';
sp_executesql @sql,
                   N'@offset int, @newsize int',
                   @offset=@ofset, @newsize=@newsize

答案 1 :(得分:0)

在您的搜索条件周围有几个额外的单引号。

SET @sql = '
    WITH OrderedSet AS
    (
      SELECT *, ROW_NUMBER() OVER (ORDER BY EmpID) AS ''Index''
      from tbl_employeeDetails e,tbl_EmpAdddress a where e.FirstName LIKE ''%' + CONVERT(NVARCHAR(12), @search) + '%''  and a.EmpID=e.EmpID
    )    
    SELECT * FROM OrderedSet WHERE [Index] BETWEEN ' + CONVERT(NVARCHAR(12), @offset) + ' AND ' + CONVERT(NVARCHAR(12), (@offset + @newsize))