我应该如何为动态SQL编写存储过程。此代码不返回任何行,并在@EmpCode
附近显示错误的语法基本查询位于http://sqlfiddle.com/#!3/6ad02e/9。如果没有,则将行转换为cols。 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'
答案 0 :(得分: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'
答案 1 :(得分: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'