0

我应该如何为动态 SQL 编写存储过程。此代码不返回任何行,并且在 @EmpCode 附近显示不正确的语法

基本查询位于http://sqlfiddle.com/#!3/6ad02e/9。如果不是,则将行转换为列。cols 是未知的。我正在尝试将参数发送到同一个查询,只是添加了“粗体”代码......

set @query = '**DECLARE @CompanyId uniqueidentifier = null,   
                      @EmpCode nvarchar(50) = null
               IF @CompanyId='+'00000000-0000-0000-0000-000000000000'+'
               SET @CompanyId = NULL
               IF @EmpCode = '+''+'
               SET @EmpCode = NULL**

              SELECT id, name,' + @cols + ' 
        from 
        (
          select e.id, e.name, lt.type, l.days 
          from tblEmp e
          left outer join tblEmpLeaves l 
            on e.id = l.empId
          left outer join tblLeaveType lt 
            on l.leaveId = lt.Id
          **WHERE
            (E.Deleted = 0) AND
            (E.EmpCompanyId = @CompanyId OR @CompanyId IS NULL)AND
            (E.EmpCode LIKE %@EmpCode% OR @EmpCode IS NULL)**
        ) x
        pivot 
        (
            max(days)
            for type in (' + @cols + ')
        ) p 
        order by id'
4

2 回答 2

2

看来您没有正确转义引号。以下工作没有错误:

set @query = '
DECLARE @CompanyId uniqueidentifier = null,   
                      @EmpCode nvarchar(50) = null
               IF @CompanyId=''00000000-0000-0000-0000-000000000000''
               SET @CompanyId = NULL 
               IF @EmpCode =''''
               SET @EmpCode = NULL 
SELECT id, name,' + @cols + ' 
            from 
            (
              select e.id, e.name, lt.type, l.days 
              from tblEmp e
              left outer join tblEmpLeaves l 
                on e.id = l.empId
              left outer join tblLeaveType lt 
                on l.leaveId = lt.Id
            ) x
            pivot 
            (
                max(days)
                for type in (' + @cols + ')
            ) p 
            order by id'

http://sqlfiddle.com/#!3/6ad02e/29/0

于 2013-11-11T16:34:03.013 回答
0

尝试这个:

set @query = 'DECLARE @CompanyId uniqueidentifier = null,   
                      @EmpCode nvarchar(50) = null
               IF @CompanyId='+'00000000-0000-0000-0000-000000000000'+'
               SET @CompanyId = NULL
               IF @EmpCode = '+''+'
               SET @EmpCode = NULL**

              SELECT id, name,' + @cols + ' 
        from 
        (
          select e.id, e.name, lt.type, l.days 
          from tblEmp e
          left outer join tblEmpLeaves l 
            on e.id = l.empId
          left outer join tblLeaveType lt 
            on l.leaveId = lt.Id
          WHERE
            (E.Deleted = 0) AND
            (E.EmpCompanyId = @CompanyId OR @CompanyId IS NULL)AND
            (E.EmpCode LIKE %+@EmpCode+% OR @EmpCode IS NULL)**
        ) x
        pivot 
        (
            max(days)
            for type in (' + @cols + ')
        ) p 
        order by id'
于 2013-11-11T15:42:42.210 回答