我尝试在MS服务器管理工作室中运行以下脚本,这非常正常。
SELECT ucb.UserFirstName, ucb.UserLastName, ucb.userid, c.caseid
FROM Cases c
LEFT JOIN Users ucb ON (c.ConfirmedBy=ucb.UserID)
JOIN RealtorStaff rs ON c.realtorstaffid=rs.realtorstaffid
WHERE c.ConfirmedBy is not null AND c.CaseStatusID <> 7
AND (
SELECT COUNT(ServiceID)
FROM Cases ca JOIN Services s ON ca.CaseID=s.CaseID
WHERE ca.CaseID=c.CaseID
AND s.ServiceTypeID != 8
AND s.ServiceTypeID != 9
AND s.ServiceTypeID != 10
AND s.ServiceTypeID != 14
AND s.ServiceTypeID != 15
AND s.ServiceStatusID != 7)>0
AND c.DateConfirmed >= '2010-08-06 00:00:00'
AND c.DateConfirmed <= '2010-08-06 23:59:59'
ORDER BY ucb.UserFirstName, ucb.UserLastName, c.caseid
在我尝试将其转换为以下脚本之后不知何故,以便我可以在sp_executesql和错误消息显示下运行它(消息102,级别15,状态1,行11 '8'附近的语法不正确。
-- /* for testing purpose
Declare @startdate DATETIME; set @startdate = '2010-08-06'
Declare @enddate DATETIME; set @enddate = '2010-08-06'
-- */
Declare @actualstartdate varchar(20); set @actualstartdate = replace(convert(char(26),@startdate,102),'.','-')+' 00:00:00'
Declare @actualenddate varchar(20); set @actualenddate = replace(convert(char(26),@enddate,102),'.','-')+' 23:59:58'
DECLARE @SQL nvarchar(500)
SET @SQL = 'SELECT ucb.UserFirstName, ucb.UserLastName, ucb.userid, c.caseid
INTO ##actual_assigned_cases
FROM Cases c
LEFT JOIN Users ucb ON (c.ConfirmedBy=ucb.UserID)
JOIN RealtorStaff rs ON c.realtorstaffid=rs.realtorstaffid
WHERE c.ConfirmedBy is not null '
SET @SQL = @SQL+' AND c.CaseStatusID <> 7
AND (SELECT COUNT(ServiceID)
FROM Cases ca
JOIN Services s ON ca.CaseID=s.CaseID
WHERE ca.CaseID=c.CaseID
AND s.ServiceTypeID != 8
AND s.ServiceTypeID != 9
AND s.ServiceTypeID != 10
AND s.ServiceTypeID != 14
AND s.ServiceTypeID != 15
AND s.ServiceStatusID != 7) > 0'
SET @SQL = @SQL+' AND c.DateConfirmed >= '''+@actualstartdate+'''
AND c.DateConfirmed <= '''+@actualenddate+'''
ORDER BY ucb.UserFirstName, ucb.UserLastName, c.caseid'
EXECUTE sp_executesql @SQL
有谁知道这里发生了什么?以及如何解决这个问题?
答案 0 :(得分:3)
做一个print @sql
AKA the poor man's debugger
并且问题将会显露出来,我的猜测是nvarchar(500)还不够......等于2000
另请查看Changing exec to sp_executesql doesn't provide any benefit if you are not using parameters correctly以了解如何使用参数以便可以重复使用执行计划
答案 1 :(得分:2)
您是否尝试过打印@SQL以查看变量内部的内容?
拿走你所拥有的东西并打印出来,我明白了:
SELECT ucb.UserFirstName, ucb.UserLastName, ucb.userid, c.caseid
INTO ##actual_assigned_cases
FROM Cases c
LEFT JOIN Users ucb ON (c.ConfirmedBy=ucb.UserID)
JOIN RealtorStaff rs ON c.realtorstaffid=rs.realtorstaffid
WHERE c.ConfirmedBy is not null AND c.CaseStatusID <> 7
AND (SELECT COUNT(ServiceID)
FROM Cases ca
JOIN Services s ON ca.CaseI
看起来你的@SQL变量不够大 - 试试nvarchar(max)。
答案 2 :(得分:2)
您有超过500个字符,因此@SQL
被截断
改为:
DECLARE @SQL nvarchar(4000)