Maximum length is 8000 in microsoft sql server management studio [closed] - sql-server

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
So i have an error found in my procedure where my query string part of the OPENQUERY is exceeding the maximum defined limits of 8000 characters. What can I do?
The error
The character string that starts with 'select distinct UPPER (case when cast(i.attendantaddress as varchar(30)) is null then i.specialnotes else cast(i.attendantaddress' is too long. Maximum length is 8000.--
The stored procedure
CREATE procedure [dbo].[proc_GetFreePatients1_20apr]
as
declare #temp table(CONTROLNO varchar(max), UHID varchar(250),PATIENTNAME varchar(250),AGE INT,GENDER VARCHAR(1),ADRESS varchar(500),CONTACTNUMBER varchar(20),IPID varchar(20),BED varchar(20),REASONFORADMISSION varchar(max),DIAGNOSIS varchar(max),ADMITDATETIME datetime,DOCTOR varchar(150),
SPECIALITY varchar(500),REFERREDDOCTOR varchar(500),RECOMMENDEDBY varchar(500),EMERGENCYCOLDCASE varchar(500),WARD varchar(150))
insert #temp
select * from openquery(ahdelwards,'select distinct UPPER (case when cast(i.attendantaddress as varchar(30)) is null then i.specialnotes else cast(i.attendantaddress as varchar(30)) end) CONTROLNO,pm.registrationno,
rp.firstname||'' ''||rp.middlename||'' ''||rp.lastname as Patientname,rp.age,
(case when rp.gender=71 then ''F''
else ''M'' end ) GENDER,
ad.address1||'',''||ad.address2||'',''||c.cityname||'',''||sm.statename ADRESS,
(case when ad.residencenumber is null then
(case when ad.emergencynumber is null then ad.mobilenumber
when ad.emergencynumber is not null then ad.emergencynumber
when ad.mobilenumber is null then ad.emergencynumber
when ad.mobilenumber is not null then ad.mobilenumber end) else ad.residencenumber end) CONTACTNUMBER,
i.inpatientno,
bm.bedcode,
I.REASONFORADMISSION,
(select dt.parametervalue
from wards.dischargesummdtls dt
where dt.parammappingid in
(select pm.parammappingid
from wards.parametermapping pm
where pm.parameterid = 1299)
and dt.status = 1
and dt.dischargeno in
(select dy.dischargeno
from wards.dischargesumm_dync dy
where dy.ipno = i.inpatientno)) diagnosis,
i.dateofadmission,
e.FIRSTNAME||'' ''||e.MIDDLENAME||'' ''||e.LASTNAME as doctor,
f_getspeciality(i.admittingdoctor)Speciality,
f_getemployeename(i.referreddoctor)referreddoctor,
UPPER(i.wardnurse) RECOMMENDEDBY,
UPPER(i.housekeeping) EMERGENCYCOLDCASE,
l.leveldetailname
from billing.pateintpolicydetails pd
left join billing.patientpolicymaster pm
on pd.policymasterid = pm.patientpolicymasterid
and pd.policystatus = 1
and pd.aggrementid = 60429
join adt.inpatientmaster i
on i.uhid = pm.registrationno
join registration.patient rp
on rp.uhid = i.uhid
join
registration.addressmaster ad on rp.registrationid=ad.registrationid and ad.addresstypeid=''2'' and ad.status=''1''
inner join
ehis.countrymaster cm on cm.countrycode=ad.country
inner join
ehis.statemaster sm on sm.statecode=ad.state and sm.status=''1''
inner join
ehis.districtmaster dm on dm.districtcode=ad.district and dm.status=''1'' and dm.stateid=sm.stateid
inner join
ehis.citymaster c on c.citycode=ad.city and c.status=''1'' and c.districtid=dm.districtid
join adt.bedmaster bm
on bm.bedid = i.bedid
join hr.employee_main_details e
on e.employeeid = i.admittingdoctor
join adt.leveldetail l
on l.leveldetailid = bm.leveldetailid
where pm.locationid = 10701
and i.locationid = 10701
and i.status not in (7,11)
union
select distinct UPPER (case when cast(i.attendantaddress as varchar(30)) is null then i.specialnotes else cast(i.attendantaddress as varchar(30)) end) CONTROLNO,pm.registrationno,
rp.firstname||'' ''||rp.middlename||'' ''||rp.lastname as Patientname,rp.age, (case when rp.gender=71 then ''F''
else ''M'' end ) GENDER,
ad.address1||'',''||ad.address2||'',''||c.cityname||'',''||sm.statename ADRESS,
(case when ad.residencenumber is null then
(case when ad.emergencynumber is null then ad.mobilenumber
when ad.emergencynumber is not null then ad.emergencynumber
when ad.mobilenumber is null then ad.emergencynumber
when ad.mobilenumber is not null then ad.mobilenumber end) else ad.residencenumber end) CONTACTNUMBER,i.inpatientno,
bm.bedcode,
I.REASONFORADMISSION,
(select dt.parametervalue
from wards.dischargesummdtls dt
where dt.parammappingid in
(select pm.parammappingid
from wards.parametermapping pm
where pm.parameterid = 1299)
and dt.status = 1
and dt.dischargeno in
(select dy.dischargeno
from wards.dischargesumm_dync dy
where dy.ipno = i.inpatientno)) diagnosis,
i.dateofadmission,
e.FIRSTNAME||'' ''||e.MIDDLENAME||'' ''||e.LASTNAME as doctor,
f_getspeciality(i.admittingdoctor)Speciality,
f_getemployeename(i.referreddoctor)referreddoctor,
UPPER(i.wardnurse) RECOMMENDEDBY,
UPPER(i.housekeeping) EMERGENCYCOLDCASE,
l.leveldetailname
from billing.pateintpolicydetails pd
full outer join billing.patientpolicymaster pm
on pd.policymasterid = pm.patientpolicymasterid
and pd.policystatus = 1
join adt.inpatientmaster i
on i.uhid = pm.registrationno
join registration.patient rp
on rp.uhid = i.uhid
join
registration.addressmaster ad on rp.registrationid=ad.registrationid and ad.addresstypeid=''2'' and ad.status=''1''
inner join
ehis.countrymaster cm on cm.countrycode=ad.country
inner join
ehis.statemaster sm on sm.statecode=ad.state and sm.status=''1''
inner join
ehis.districtmaster dm on dm.districtcode=ad.district and dm.status=''1'' and dm.stateid=sm.stateid
inner join
ehis.citymaster c on c.citycode=ad.city and c.status=''1'' and c.districtid=dm.districtid
join adt.bedmaster bm
on bm.bedid = i.bedid
join hr.employee_main_details e
on e.employeeid = i.admittingdoctor
join adt.leveldetail l
on l.leveldetailid = bm.leveldetailid
and l.leveldetailid not in (221,257)
where i.freepatient = 1
and pm.locationid = 10701
and i.locationid = 10701
and i.status not in (7,11)
union
select distinct UPPER (case when cast(i.attendantaddress as varchar(30)) is null then i.specialnotes else cast(i.attendantaddress as varchar(30)) end) CONTROLNO,pm.registrationno,
rp.firstname||'' ''||rp.middlename||'' ''||rp.lastname as Patientname,rp.age, (case when rp.gender=71 then ''F''
else ''M'' end ) GENDER,
ad.address1||'',''||ad.address2||'',''||c.cityname||'',''||sm.statename ADRESS,
(case when ad.residencenumber is null then
(case when ad.emergencynumber is null then ad.mobilenumber
when ad.emergencynumber is not null then ad.emergencynumber
when ad.mobilenumber is null then ad.emergencynumber
when ad.mobilenumber is not null then ad.mobilenumber end) else ad.residencenumber end) CONTACTNUMBER,
i.inpatientno,
bm.bedcode,
I.REASONFORADMISSION,
(select dt.parametervalue
from wards.dischargesummdtls dt
where dt.parammappingid in
(select pm.parammappingid
from wards.parametermapping pm
where pm.parameterid = 1299)
and dt.status = 1
and dt.dischargeno in
(select dy.dischargeno
from wards.dischargesumm_dync dy
where dy.ipno = i.inpatientno)) diagnosis,
i.dateofadmission,
e.FIRSTNAME||'' ''||e.MIDDLENAME||'' ''||e.LASTNAME as doctor,
f_getspeciality(i.admittingdoctor)Speciality,
f_getemployeename(i.referreddoctor)referreddoctor,
UPPER(i.wardnurse) RECOMMENDEDBY,
UPPER(i.housekeeping) EMERGENCYCOLDCASE,
l.leveldetailname
from billing.pateintpolicydetails pd
full outer join billing.patientpolicymaster pm
on pd.policymasterid = pm.patientpolicymasterid
and pd.policystatus = 1
join adt.inpatientmaster i
on i.uhid = pm.registrationno
join registration.patient rp
on rp.uhid = i.uhid
join
registration.addressmaster ad on rp.registrationid=ad.registrationid and ad.addresstypeid=''2'' and ad.status=''1''
inner join
ehis.countrymaster cm on cm.countrycode=ad.country
inner join
ehis.statemaster sm on sm.statecode=ad.state and sm.status=''1''
inner join
ehis.districtmaster dm on dm.districtcode=ad.district and dm.status=''1'' and dm.stateid=sm.stateid
inner join
ehis.citymaster c on c.citycode=ad.city and c.status=''1'' and c.districtid=dm.districtid
join adt.bedmaster bm
on bm.bedid = i.bedid
join hr.employee_main_details e
on e.employeeid = i.admittingdoctor
join adt.leveldetail l
on l.leveldetailid = bm.leveldetailid
and l.leveldetailid in (221,257)
where i.freepatient = 1
and pm.locationid = 10701
and i.locationid = 10701
and i.status not in (7,11)
')
--pd.aggrementid IN (60429,7140)
select distinct * from #temp order by 11 asc

Declare #strSQL varchar(max)
set #strSQL = N'<your query here>'
exec #strSQL at <YourLinkedServerName>
This bypasses any limitation of the 8000 character limit.
May be something like below:
CREATE PROCEDURE [dbo].[proc_GetFreePatients1_20apr]
AS
BEGIN
DECLARE #temp TABLE(CONTROLNO varchar(max), UHID varchar(250),PATIENTNAME varchar(250),AGE INT,GENDER VARCHAR(1),ADRESS varchar(500),
CONTACTNUMBER varchar(20),IPID varchar(20),BED varchar(20),REASONFORADMISSION varchar(max),DIAGNOSIS varchar(max),
ADMITDATETIME datetime,DOCTOR varchar(150),SPECIALITY varchar(500),REFERREDDOCTOR varchar(500),RECOMMENDEDBY varchar(500),
EMERGENCYCOLDCASE varchar(500),WARD varchar(150))
DECLARE #strSQL VARCHAR(MAX)
SET #strSQL = N'SELECT DISTINCT Upper (
CASE
WHEN Cast(i.attendantaddress AS VARCHAR(30)) IS NULL THEN i.specialnotes
ELSE Cast(i.attendantaddress AS VARCHAR(30))
END) controlno,
pm.registrationno,
rp.firstname
||'' ''
||rp.middlename
||'' ''
||rp.lastname AS patientname,
rp.age, (
CASE
WHEN rp.gender=71 THEN ''f''
ELSE ''m''
END ) gender,
ad.address1
||'',
''
||ad.address2
||'',
''
||c.cityname
||'',
''
||sm.statename adress, (
CASE
WHEN ad.residencenumber IS NULL THEN (
CASE
WHEN ad.emergencynumber IS NULL THEN ad.mobilenumber
WHEN ad.emergencynumber IS NOT NULL THEN ad.emergencynumber
WHEN ad.mobilenumber IS NULL THEN ad.emergencynumber
WHEN ad.mobilenumber IS NOT NULL THEN ad.mobilenumber
END)
ELSE ad.residencenumber
END) contactnumber,
i.inpatientno,
bm.bedcode,
i.reasonforadmission,
(
SELECT dt.parametervalue
FROM wards.dischargesummdtls dt
WHERE dt.parammappingid IN
(
SELECT pm.parammappingid
FROM wards.parametermapping pm
WHERE pm.parameterid = 1299)
AND dt.status = 1
AND dt.dischargeno IN
(
SELECT dy.dischargeno
FROM wards.dischargesumm_dync dy
WHERE dy.ipno = i.inpatientno)) diagnosis,
i.dateofadmission,
e.firstname
||'' ''
||e.middlename
||'' ''
||e.lastname AS doctor,
f_getspeciality(i.admittingdoctor) speciality,
f_getemployeename(i.referreddoctor) referreddoctor,
upper(i.wardnurse) recommendedby,
upper(i.housekeeping) emergencycoldcase,
l.leveldetailname
FROM billing.pateintpolicydetails pd
LEFT JOIN billing.patientpolicymaster pm
ON pd.policymasterid = pm.patientpolicymasterid
AND pd.policystatus = 1
AND pd.aggrementid = 60429
JOIN adt.inpatientmaster i
ON i.uhid = pm.registrationno
JOIN registration.patient rp
ON rp.uhid = i.uhid
JOIN registration.addressmaster ad
ON rp.registrationid=ad.registrationid
AND ad.addresstypeid=''2''
AND ad.status=''1''
INNER JOIN ehis.countrymaster cm
ON cm.countrycode=ad.country
INNER JOIN ehis.statemaster sm
ON sm.statecode=ad.state
AND sm.status=''1''
INNER JOIN ehis.districtmaster dm
ON dm.districtcode=ad.district
AND dm.status=''1''
AND dm.stateid=sm.stateid
INNER JOIN ehis.citymaster c
ON c.citycode=ad.city
AND c.status=''1''
AND c.districtid=dm.districtid
JOIN adt.bedmaster bm
ON bm.bedid = i.bedid
JOIN hr.employee_main_details e
ON e.employeeid = i.admittingdoctor
JOIN adt.leveldetail l
ON l.leveldetailid = bm.leveldetailid
WHERE pm.locationid = 10701
AND i.locationid = 10701
AND i.status NOT IN (7,11)
UNION
SELECT DISTINCT upper (
CASE
WHEN cast(i.attendantaddress AS varchar(30)) IS NULL THEN i.specialnotes
ELSE cast(i.attendantaddress AS varchar(30))
END) controlno,
pm.registrationno,
rp.firstname
||'' ''
||rp.middlename
||'' ''
||rp.lastname AS patientname,
rp.age, (
CASE
WHEN rp.gender=71 THEN ''f''
ELSE ''m''
END ) gender,
ad.address1
||'',
''
||ad.address2
||'',
''
||c.cityname
||'',
''
||sm.statename adress, (
CASE
WHEN ad.residencenumber IS NULL THEN (
CASE
WHEN ad.emergencynumber IS NULL THEN ad.mobilenumber
WHEN ad.emergencynumber IS NOT NULL THEN ad.emergencynumber
WHEN ad.mobilenumber IS NULL THEN ad.emergencynumber
WHEN ad.mobilenumber IS NOT NULL THEN ad.mobilenumber
END)
ELSE ad.residencenumber
END) contactnumber,
i.inpatientno,
bm.bedcode,
i.reasonforadmission,
(
SELECT dt.parametervalue
FROM wards.dischargesummdtls dt
WHERE dt.parammappingid IN
(
SELECT pm.parammappingid
FROM wards.parametermapping pm
WHERE pm.parameterid = 1299)
AND dt.status = 1
AND dt.dischargeno IN
(
SELECT dy.dischargeno
FROM wards.dischargesumm_dync dy
WHERE dy.ipno = i.inpatientno)) diagnosis,
i.dateofadmission,
e.firstname
||'' ''
||e.middlename
||'' ''
||e.lastname AS doctor,
f_getspeciality(i.admittingdoctor) speciality,
f_getemployeename(i.referreddoctor) referreddoctor,
upper(i.wardnurse) recommendedby,
upper(i.housekeeping) emergencycoldcase,
l.leveldetailname
FROM billing.pateintpolicydetails pd
FULL OUTER JOIN billing.patientpolicymaster pm
ON pd.policymasterid = pm.patientpolicymasterid
AND pd.policystatus = 1
JOIN adt.inpatientmaster i
ON i.uhid = pm.registrationno
JOIN registration.patient rp
ON rp.uhid = i.uhid
JOIN registration.addressmaster ad
ON rp.registrationid=ad.registrationid
AND ad.addresstypeid=''2''
AND ad.status=''1''
INNER JOIN ehis.countrymaster cm
ON cm.countrycode=ad.country
INNER JOIN ehis.statemaster sm
ON sm.statecode=ad.state
AND sm.status=''1''
INNER JOIN ehis.districtmaster dm
ON dm.districtcode=ad.district
AND dm.status=''1''
AND dm.stateid=sm.stateid
INNER JOIN ehis.citymaster c
ON c.citycode=ad.city
AND c.status=''1''
AND c.districtid=dm.districtid
JOIN adt.bedmaster bm
ON bm.bedid = i.bedid
JOIN hr.employee_main_details e
ON e.employeeid = i.admittingdoctor
JOIN adt.leveldetail l
ON l.leveldetailid = bm.leveldetailid
AND l.leveldetailid NOT IN (221,257)
WHERE i.freepatient = 1
AND pm.locationid = 10701
AND i.locationid = 10701
AND i.status NOT IN (7,11)
UNION
SELECT DISTINCT upper (
CASE
WHEN cast(i.attendantaddress AS varchar(30)) IS NULL THEN i.specialnotes
ELSE cast(i.attendantaddress AS varchar(30))
END) controlno,
pm.registrationno,
rp.firstname
||'' ''
||rp.middlename
||'' ''
||rp.lastname AS patientname,
rp.age, (
CASE
WHEN rp.gender=71 THEN ''f''
ELSE ''m''
END ) gender,
ad.address1
||'',
''
||ad.address2
||'',
''
||c.cityname
||'',
''
||sm.statename adress, (
CASE
WHEN ad.residencenumber IS NULL THEN (
CASE
WHEN ad.emergencynumber IS NULL THEN ad.mobilenumber
WHEN ad.emergencynumber IS NOT NULL THEN ad.emergencynumber
WHEN ad.mobilenumber IS NULL THEN ad.emergencynumber
WHEN ad.mobilenumber IS NOT NULL THEN ad.mobilenumber
END)
ELSE ad.residencenumber
END) contactnumber,
i.inpatientno,
bm.bedcode,
i.reasonforadmission,
(
SELECT dt.parametervalue
FROM wards.dischargesummdtls dt
WHERE dt.parammappingid IN
(
SELECT pm.parammappingid
FROM wards.parametermapping pm
WHERE pm.parameterid = 1299)
AND dt.status = 1
AND dt.dischargeno IN
(
SELECT dy.dischargeno
FROM wards.dischargesumm_dync dy
WHERE dy.ipno = i.inpatientno)) diagnosis,
i.dateofadmission,
e.firstname
||'' ''
||e.middlename
||'' ''
||e.lastname AS doctor,
f_getspeciality(i.admittingdoctor) speciality,
f_getemployeename(i.referreddoctor) referreddoctor,
upper(i.wardnurse) recommendedby,
upper(i.housekeeping) emergencycoldcase,
l.leveldetailname
FROM billing.pateintpolicydetails pd
FULL OUTER JOIN billing.patientpolicymaster pm
ON pd.policymasterid = pm.patientpolicymasterid
AND pd.policystatus = 1
JOIN adt.inpatientmaster i
ON i.uhid = pm.registrationno
JOIN registration.patient rp
ON rp.uhid = i.uhid
JOIN registration.addressmaster ad
ON rp.registrationid=ad.registrationid
AND ad.addresstypeid=''2''
AND ad.status=''1''
INNER JOIN ehis.countrymaster cm
ON cm.countrycode=ad.country
INNER JOIN ehis.statemaster sm
ON sm.statecode=ad.state
AND sm.status=''1''
INNER JOIN ehis.districtmaster dm
ON dm.districtcode=ad.district
AND dm.status=''1''
AND dm.stateid=sm.stateid
INNER JOIN ehis.citymaster c
ON c.citycode=ad.city
AND c.status=''1''
AND c.districtid=dm.districtid
JOIN adt.bedmaster bm
ON bm.bedid = i.bedid
JOIN hr.employee_main_details e
ON e.employeeid = i.admittingdoctor
JOIN adt.leveldetail l
ON l.leveldetailid = bm.leveldetailid
AND l.leveldetailid IN (221,257)
WHERE i.freepatient = 1
AND pm.locationid = 10701
AND i.locationid = 10701
AND i.status NOT IN (7,11)'
INSERT #temp
SELECT * FROM OPENQUERY(ahdelwards,#strSQL)
SELECT DISTINCT * FROM #temp ORDER BY 11 ASC
END

Related

Stored Procedure "spins" when executed from Visual Studio 2012

I have written 3 stored procedures and all run fine when executed in SQL Server. However, when I execute them in Visual Studio 2012 they just "spin", creating locks, etc. Any ideas?
Here is one of them. Another one is selecting values from an inline view based on the same SQL and not inserting into #temp
#StartDate As DateTime,
#EndDate As DateTime,
#EmployeeCode As VarChar(50) = NULL
AS
BEGIN
SET NOCOUNT ON;
select * into #temp
from
(SELECT e.Code AS EMPLOYEE_ID,
e.FirstName AS FIRST_NAME,
e.LastName AS LAST_NAME,
ec1.TransactionDate AS DATE_OF_SHIFT,
ou.Code AS DEPT_UNIT_CODE,
CASE
WHEN ec1.Classification = '1' THEN
MIN(ec1.TransactionDate)
END AS CLOCK_IN,
CASE
WHEN ec2.Classification = '2' THEN
MAX(ec2.TransactionDate)
END AS CLOCK_OUT,
pc.code,
epb.hourvalue
FROM APIHealthcare_History_Live.dbo.Employee e (nolock)
JOIN APIHealthcare_Live.dbo.EmployeeClocking ec1 (nolock)
ON ec1.EmployeeID = e.ID
JOIN APIHealthcare_Live.dbo.EmployeeClocking ec2 (nolock)
ON ec1.OutClockingGuid = ec2.Guid
JOIN APIHealthcare_Live.dbo.OrganizationUnit ou (nolock)
ON ec1.OrganizationUnitID = ou.ID
LEFT JOIN APIHealthcare_Live.dbo.EmployeePremiumBucket epb (nolock)
ON ec1.Guid = epb.TransactionGuid
JOIN APIHealthcare_Live.dbo.PayCode pc (nolock)
ON epb.PayCodeID = pc.ID
JOIN APIHealthcare_Live.dbo.PayGroupInstance pgi (nolock)
ON pgi.ID = epb.PayGroupInstanceID
WHERE
ec1.transactiondate between #StartDate and #EndDate
and epb.PaymentClassification = '1'
AND e.code = #EmployeeCode
AND e.ArchiveTaskID =
(
SELECT MAX(e2.ArchiveTaskID)
FROM APIHealthcare_History_Live.dbo.Employee e2 (NOLOCK)
WHERE e2.ID = e.ID
)
GROUP BY e.Code,
e.FirstName,
e.LastName,
ec1.TransactionDate,
ou.Code,
ec1.Classification,
ec2.Classification,
pc.code,
epb.hourvalue
UNION
SELECT e.Code AS EMPLOYEE_ID,
e.FirstName AS FIRST_NAME,
e.LastName AS LAST_NAME,
ec1.TransactionDate AS DATE_OF_SHIFT,
ou.Code AS DEPT_UNIT_CODE,
CASE
WHEN ec1.Classification = '1' THEN
MIN(ec1.TransactionDate)
END AS CLOCK_IN,
CASE
WHEN ec2.Classification = '2' THEN
MAX(ec2.TransactionDate)
END AS CLOCK_OUT,
pc.code,
epb.hourvalue
FROM APIHealthcare_History_Live.dbo.Employee e (nolock)
JOIN APIHealthcare_History_Live.dbo.EmployeeClocking ec1 (nolock)
ON ec1.EmployeeID = e.ID
JOIN APIHealthcare_History_Live.dbo.EmployeeClocking ec2 (nolock)
ON ec1.OutClockingGuid = ec2.Guid
JOIN APIHealthcare_History_Live.dbo.OrganizationUnit ou (nolock)
ON ec1.OrganizationUnitID = ou.ID
LEFT JOIN APIHealthcare_History_Live.dbo.EmployeePremiumBucket epb (nolock)
ON ec1.Guid = epb.TransactionGuid
JOIN APIHealthcare_History_Live.dbo.PayCode pc (nolock)
ON epb.PayCodeID = pc.ID
JOIN APIHealthcare_History_Live.dbo.PayGroupInstance pgi (nolock)
ON pgi.ID = epb.PayGroupInstanceID
WHERE
ec1.transactiondate between #StartDate and #EndDate
and epb.PaymentClassification = '1'
AND e.code = #EmployeeCode
AND e.ArchiveTaskID =
(
SELECT MAX(e2.ArchiveTaskID)
FROM APIHealthcare_History_Live.dbo.Employee e2 (NOLOCK)
WHERE e2.ID = e.ID
)
AND ou.ArchiveTaskID =
(
SELECT MAX(ou2.ArchiveTaskID)
FROM APIHealthcare_History_Live.dbo.OrganizationUnit ou2 (NOLOCK)
WHERE ou2.ID = ou.ID
)
AND pc.ArchiveTaskID =
(
SELECT MAX(pc2.ArchiveTaskID)
FROM APIHealthcare_History_Live.dbo.PayCode pc2 (NOLOCK)
WHERE pc2.ID = pc.ID
)
GROUP BY e.Code,
e.FirstName,
e.LastName,
ec1.TransactionDate,
ou.Code,
ec1.Classification,
ec2.Classification,
pc.code,
epb.hourvalue) as X
select EMPLOYEE_ID,
FIRST_NAME,
LAST_NAME,
DATE_OF_SHIFT,
DEPT_UNIT_CODE,
CLOCK_IN,
CLOCK_OUT,
code,
sum(hourvalue) as Hours
from #temp
group by EMPLOYEE_ID,
FIRST_NAME,
LAST_NAME,
DATE_OF_SHIFT,
DEPT_UNIT_CODE,
CLOCK_IN,
CLOCK_OUT,
CODE
Order by CLOCK_OUT
END
Here is the other one.
#StartDate As DateTime,
#EndDate As DateTime,
#EmployeeCode As VarChar(50) = NULL
AS
BEGIN
SET NOCOUNT ON;
select EMPLOYEE_ID,
FIRST_NAME,
LAST_NAME,
DATE_OF_SHIFT,
DEPT_UNIT_CODE,
CLOCK_IN,
CLOCK_OUT,
code,
sum(hourvalue) as Hours
from
(
SELECT e.Code AS EMPLOYEE_ID,
e.FirstName AS FIRST_NAME,
e.LastName AS LAST_NAME,
ec1.TransactionDate AS DATE_OF_SHIFT,
ou.Code AS DEPT_UNIT_CODE,
CASE
WHEN ec1.Classification = '1' THEN
MIN(ec1.TransactionDate)
END AS CLOCK_IN,
CASE
WHEN ec2.Classification = '2' THEN
MAX(ec2.TransactionDate)
END AS CLOCK_OUT,
pc.code,
epb.hourvalue
FROM APIHealthcare_History_Live.dbo.Employee e
JOIN APIHealthcare_Live.dbo.EmployeeClocking ec1
ON ec1.EmployeeID = e.ID
JOIN APIHealthcare_Live.dbo.EmployeeClocking ec2
ON ec1.OutClockingGuid = ec2.Guid
JOIN APIHealthcare_Live.dbo.OrganizationUnit ou
ON ec1.OrganizationUnitID = ou.ID
LEFT JOIN APIHealthcare_Live.dbo.EmployeePremiumBucket epb
ON ec1.Guid = epb.TransactionGuid
JOIN APIHealthcare_Live.dbo.PayCode pc
ON epb.PayCodeID = pc.ID
JOIN APIHealthcare_Live.dbo.PayGroupInstance pgi
ON pgi.ID = epb.PayGroupInstanceID
WHERE ec1.transactiondate between #StartDate and #EndDate
and epb.PaymentClassification = '1'
AND e.code = #EmployeeCode
AND e.ArchiveTaskID =
(
SELECT MAX(e2.ArchiveTaskID)
FROM APIHealthcare_History_Live.dbo.Employee e2 (NOLOCK)
WHERE e2.ID = e.ID
)
GROUP BY e.Code,
e.FirstName,
e.LastName,
ec1.TransactionDate,
ou.Code,
ec1.Classification,
ec2.Classification,
pc.code,
epb.hourvalue
UNION
SELECT e.Code AS EMPLOYEE_ID,
e.FirstName AS FIRST_NAME,
e.LastName AS LAST_NAME,
ec1.TransactionDate AS DATE_OF_SHIFT,
ou.Code AS DEPT_UNIT_CODE,
CASE
WHEN ec1.Classification = '1' THEN
MIN(ec1.TransactionDate)
END AS CLOCK_IN,
CASE
WHEN ec2.Classification = '2' THEN
MAX(ec2.TransactionDate)
END AS CLOCK_OUT,
pc.code,
epb.hourvalue
FROM APIHealthcare_History_Live.dbo.Employee e
JOIN APIHealthcare_History_Live.dbo.EmployeeClocking ec1
ON ec1.EmployeeID = e.ID
JOIN APIHealthcare_History_Live.dbo.EmployeeClocking ec2
ON ec1.OutClockingGuid = ec2.Guid
JOIN APIHealthcare_History_Live.dbo.OrganizationUnit ou
ON ec1.OrganizationUnitID = ou.ID
LEFT JOIN APIHealthcare_History_Live.dbo.EmployeePremiumBucket epb
ON ec1.Guid = epb.TransactionGuid
JOIN APIHealthcare_History_Live.dbo.PayCode pc
ON epb.PayCodeID = pc.ID
JOIN APIHealthcare_History_Live.dbo.PayGroupInstance pgi
ON pgi.ID = epb.PayGroupInstanceID
WHERE ec1.transactiondate between #StartDate and #EndDate
and epb.PaymentClassification = '1'
AND e.code = #EmployeeCode
AND e.ArchiveTaskID =
(
SELECT MAX(e2.ArchiveTaskID)
FROM APIHealthcare_History_Live.dbo.Employee e2 (NOLOCK)
WHERE e2.ID = e.ID
)
AND ou.ArchiveTaskID =
(
SELECT MAX(ou2.ArchiveTaskID)
FROM APIHealthcare_History_Live.dbo.OrganizationUnit ou2 (NOLOCK)
WHERE ou2.ID = ou.ID
)
AND pc.ArchiveTaskID =
(
SELECT MAX(pc2.ArchiveTaskID)
FROM APIHealthcare_History_Live.dbo.PayCode pc2 (NOLOCK)
WHERE pc2.ID = pc.ID
)
GROUP BY e.Code,
e.FirstName,
e.LastName,
ec1.TransactionDate,
ou.Code,
ec1.Classification,
ec2.Classification,
pc.code,
epb.hourvalue) as X
group by
EMPLOYEE_ID,
FIRST_NAME,
LAST_NAME,
DATE_OF_SHIFT,
DEPT_UNIT_CODE,
CLOCK_IN,
CLOCK_OUT,
code
order by date_of_shift, code
END
They are different execution environments. And yes, read Sommarskog's article already recommended. But I think main reason why these procedures will be slow (and not consistently) is the UNION operator. You should use UNION ALL.
Second, get rid of these (nolock) hints. They don't help you. If you really need that, you should use
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
at the beginning of your procedure. It does the same.

SQL query is running, but stopped producing incremental results

I have the below query running in SQL Server. In a nutshell, I have 3 somewhat identical queries "unioned". When I start the query, it runs and produces incremental results in the Results pane. But, once it reaches 264,619 records (first 5 minutes), it just stops producing results, yet the query is running and has been running for 30 minutes. Any ideas why this is happening? I understand the query below is kind of long/semi-complex, so my apologies, I couldn't make it any simpler (I'm hoping someone might be able to point me in a direction that I would be able to make the query below a little simpler). Below the query is a screenshot of the results pane. I'm wondering if the query is deadlocked somewhere or running into an infinite loop/etc.:
select
Q1.[Transaction Identifier],
row_number() over (order by (select 1)) as 'Transaction Sequence Number',
Q1.HL_Acct_ID,
Q1.AcctNumber,
Q1.AcctType,
Q1.AcctSource,
Q1.DUNS_NBR,
Q1.DBPLCR_CONTACT_ID,
Q1.CellCode,
Q1.OfferCode,
Q1.ResponseType,
Q1.ResponseDate,
Q1.ResponseQuantity,
Q1.ResponseValue,
Q1.ResponseChannel,
Q1.[Cookie ID],
Q1.[IP Address],
Q1.[Device ID],
Q1.[CUSTOM_TEXT_01],
Q1.[CUSTOM_TEXT_02],
Q1.[CUSTOM_TEXT_03],
Q1.[CUSTOM_TEXT_04],
Q1.[CUSTOM_TEXT_05]
from
(
select
'ACCT PROMORESP' as 'Transaction Identifier',
s.HL_ACCT_ID as 'HL_Acct_ID',
null as [AcctNumber],
null as [AcctType],
null as [AcctSource],
null as [DUNS_NBR],
null as [DBPLCR_CONTACT_ID],
s.CELLCODE as [CellCode],
case
when c.URL is not null then c.URL
else '-1'
end as [OfferCode],
case
when c.EventDate is not null then 'Click'
when c.EventDate is null then
case
when sub.status = 'unsubscribed' then 'Unsubscribe'
when sub.status = 'bounced' then 'Bounce'
when sub.status = 'held' then 'Bounce'
end
end as [ResponseType],
convert(varchar, c.EventDate, 112) as [ResponseDate],
null as [ResponseQuantity],
null as [ResponseValue],
'Email' as [ResponseChannel],
null as [Cookie ID],
null as [IP address],
null as [Device ID],
null as [CUSTOM_TEXT_01],
null as [CUSTOM_TEXT_02],
null as [CUSTOM_TEXT_03],
null as [CUSTOM_TEXT_04],
null as [CUSTOM_TEXT_05]
from C1111111.[151222_Hostess Ensemble] s with (nolock)
inner join C1111111._subscribers sub with (nolock) on sub.SubscriberKey = s.Email
left join C1111111._click c with (nolock) on c.JobID in
(
select j.fkJobId from tblJobs_Lists j with (nolock)
inner join customobject c with (nolock) on j.customobjectid = c.customobjectid
where c.memberid = 1111111
and c.customobjectname like '151222_Hostess Ensemble'
)
and c.SubscriberKey = s.Email
where c.EventDate is not null or (c.EventDate is null and (sub.status in ('unsubscribed','bounced','held'))) and c.isunique = 1
union all
select
'ACCT PROMORESP' as 'Transaction Identifier',
s.HL_ACCT_ID as 'HL_Acct_ID',
null as [AcctNumber],
null as [AcctType],
null as [AcctSource],
null as [DUNS_NBR],
null as [DBPLCR_CONTACT_ID],
s.CELLCODE as [CellCode],
'-1' as [OfferCode],
case
when o.EventDate is not null then 'Message Open'
when o.EventDate is null then
case
when sub.status = 'unsubscribed' then 'Unsubscribe'
when sub.status = 'bounced' then 'Bounce'
when sub.status = 'held' then 'Bounce'
end
end as [ResponseType],
convert(varchar, o.EventDate, 112) as [ResponseDate],
null as [ResponseQuantity],
null as [ResponseValue],
'Email' as [ResponseChannel],
null as [Cookie ID],
null as [IP address],
null as [Device ID],
null as [CUSTOM_TEXT_01],
null as [CUSTOM_TEXT_02],
null as [CUSTOM_TEXT_03],
null as [CUSTOM_TEXT_04],
null as [CUSTOM_TEXT_05]
from C1111111.[151222_Hostess Ensemble] s with (nolock)
inner join C1111111._subscribers sub with (nolock) on sub.SubscriberKey = s.Email
left join C1111111._open o with (nolock) on o.JobID in
(
select j.fkJobId from tblJobs_Lists j with (nolock)
inner join customobject c with (nolock) on j.customobjectid = c.customobjectid
where c.memberid = 1111111
and c.customobjectname like '151222_Hostess Ensemble'
)
and o.SubscriberKey = s.Email
where o.EventDate is not null or (o.EventDate is null and (sub.status in ('unsubscribed','bounced','held'))) and o.isunique = 1
UNION ALL
select
'ACCT PROMORESP' as 'Transaction Identifier',
s.HL_ACCT_ID as 'HL_Acct_ID',
null as [AcctNumber],
null as [AcctType],
null as [AcctSource],
null as [DUNS_NBR],
null as [DBPLCR_CONTACT_ID],
s.CELLCODE as [CellCode],
'-1' as [OfferCode],
null as [ResponseType],
convert(varchar, o.EventDate, 112) as [ResponseDate],
null as [ResponseQuantity],
null as [ResponseValue],
'Email' as [ResponseChannel],
null as [Cookie ID],
null as [IP address],
null as [Device ID],
null as [CUSTOM_TEXT_01],
null as [CUSTOM_TEXT_02],
null as [CUSTOM_TEXT_03],
null as [CUSTOM_TEXT_04],
null as [CUSTOM_TEXT_05]
from C1111111.[151222_Hostess Ensemble] s with (nolock)
inner join C1111111._subscribers sub with (nolock) on sub.SubscriberKey = s.Email
left join C1111111._open o with (nolock) on o.JobID in
(
select j.fkJobId from tblJobs_Lists j with (nolock)
inner join customobject c with (nolock) on j.customobjectid = c.customobjectid
where c.memberid = 1111111
and c.customobjectname like '151222_Hostess Ensemble'
)
left join C1111111._click cl with (nolock) on o.JobID in
(
select j.fkJobId from tblJobs_Lists j with (nolock)
inner join customobject c with (nolock) on j.customobjectid = c.customobjectid
where c.memberid = 1111111
and c.customobjectname like '151222_Hostess Ensemble'
)
and cl.SubscriberKey = s.Email
where cl.EventDate is null and o.EventDate is null and sub.status not in ('unsubscribed','bounced','held')) as Q1
Without the table definitions I can't verify that this is correct, but this would be my take at a simplification of the above, with an assumption about two fixes in the join conditions:
set transaction isolation level read uncommitted;
WITH JobIDs AS
(
select j.fkJobId from tblJobs_Lists j
inner join customobject c on j.customobjectid = c.customobjectid
where c.memberid = 1111111
and c.customobjectname = '151222_Hostess Ensemble'
)
select
'ACCT PROMORESP' as 'Transaction Identifier',
row_number() over (order by (select 1)) as 'Transaction Sequence Number',
s.HL_ACCT_ID as 'HL_Acct_ID',
null as [AcctNumber],
null as [AcctType],
null as [AcctSource],
null as [DUNS_NBR],
null as [DBPLCR_CONTACT_ID],
s.CELLCODE as [CellCode],
X.OfferCode,
X.ResponseType,
convert(varchar, X.EventDate, 112) as [ResponseDate],
null as [ResponseQuantity],
null as [ResponseValue],
'Email' as [ResponseChannel],
null as [Cookie ID],
null as [IP address],
null as [Device ID],
null as [CUSTOM_TEXT_01],
null as [CUSTOM_TEXT_02],
null as [CUSTOM_TEXT_03],
null as [CUSTOM_TEXT_04],
null as [CUSTOM_TEXT_05]
from
(
SELECT
s.HL_ACCT_ID,
s.CELLCODE,
s.Email,
case sub.status
when 'unsubscribed' then 'Unsubscribe'
when 'bounced' then 'Bounce'
when 'held' then 'Bounce'
end as [ResponseType],
sub.status
from C1111111.[151222_Hostess Ensemble] s
inner join C1111111._subscribers sub on sub.SubscriberKey = s.Email
) as s
left join C1111111._open o on o.JobID in (select fkJobId from JobIDs)
-- DON'T YOU NEED A "and o.SubscriberKey = s.Email" HERE?
and o.SubscriberKey = s.Email
left join C1111111._click cl on cl.JobID in (select fkJobId from JobIDs)
-- LOOK ABOVE, was "o.JobID", **REALLY**
and cl.SubscriberKey = s.Email
cross apply (
select
'-1' as [OfferCode],
case
when o.EventDate is not null then 'Message Open'
else s.[ResponseType]
end as [ResponseType],
o.EventDate
where o.EventDate is not null or (o.EventDate is null and (s.status in ('unsubscribed','bounced','held'))) and o.isunique = 1
UNION ALL
select
isnull(cl.URL,'-1') as [OfferCode],
case
when c.EventDate is not null then 'Click'
else s.[ResponseType]
end as [ResponseType],
cl.EventDate
where cl.EventDate is not null or (cl.EventDate is null and (s.status in ('unsubscribed','bounced','held'))) and cl.isunique = 1
union all
select
'-1' as [OfferCode],
NULL AS [ResponseType],
null as EventDate
where cl.EventDate is null and o.EventDate is null and s.status not in ('unsubscribed','bounced','held')
) AS X

an expression of non-boolean type specified in a context where a condition is expected near 'type'

I am new to SSRS topics and I got this error while preparing the report plz help me to solve this. I have kept the query here kindly go through it.
SELECT T0.DocNum AS 'SO#', T6.DocNum as 'PO#', t1.LineTotal AS 'SO Amount', T6.DocEntry, T0.CardName, T6.U_enduserName, T11.QryGroup10 AS 'Major A/C Y/N',
T6.DocEntry AS Expr1, T6.CardCode, T6.CardName AS Expr2, T6.NumAtCard, T6.DocDate, t5.ItemCode, t5.Dscription, T7.U_itmdes, t5.Quantity, t5.LineTotal,
CASE WHEN T7.[U_itmdes] LIKE '%Desktop%%' THEN T5.[LineTotal] * 2.5 ELSE T5.[LineTotal] END AS 'LineTotal with DTS amt', T10.ItmsGrpNam, T8.Location,
CASE WHEN T1.[Dscription] LIKE '%Renewal%%' THEN 'Renewal' ELSE 'Product' END AS 'Lic Type'
If((((T10.ItmsGrpNam="ADESK-AEC" and T10.ItmsGrpNam="ADESK-AEC-INFRA") and T1.Lic Type="Product" and T11.QryGroup10="No")),"AEC - ENI",If(((T10.ItmsGrpNam="ADESK-OPEN" and T10.ItmsGrpNam="ADESK-HORIZONTAL") and T1.Lic Type="Product" and T11.QryGroup10="No"),"PSEB",If(((T10.ItmsGrpNam="ADESK-M&E" or T10.ItmsGrpNam="ADESK-MFG") and T1.Lic Type="Product" and T11.QryGroup10="No"),T10.ItmsGrpNam,If(((T10.ItmsGrpNam="ADESK-AEC" and T10.ItmsGrpNam="ADESK-AEC-INFRA") and T1.Lic Type="Renewal" and T11.QryGroup10="No"),"AEC & ENI - Sub Renewal",If(((T10.ItmsGrpNam="ADESK-OPEN" and T10.ItmsGrpNam="ADESK-HORIZONTAL") and T1.Lic Type="Renewal" and T11.QryGroup10="No"),"PSEB - Sub Renewal",If(((T10.ItmsGrpNam="ADESK-M&E" or T10.ItmsGrpNam="ADESK-MFG") and T1.Lic Type="Renewal" and T11.QryGroup10="No"),"MFG - Sub Renewal","MFG - Sub Renewal"))))))
FROM OCRD AS T11 INNER JOIN
ORDR AS T0 ON T11.CardCode = T0.CardCode INNER JOIN
RDR1 AS t1 ON T0.DocEntry = t1.DocEntry LEFT OUTER JOIN
POR1 AS t3 ON t3.BaseEntry = t1.DocEntry AND t3.BaseLine = t1.LineNum AND t3.ItemCode = t1.ItemCode LEFT OUTER JOIN
PDN1 AS t4 ON t4.BaseEntry = t3.DocEntry AND t4.BaseLine = t3.LineNum AND t4.ItemCode = t3.ItemCode INNER JOIN
PCH1 AS t5 ON t5.BaseEntry = t4.DocEntry AND t5.ItemCode = t4.ItemCode AND t5.BaseLine = t4.LineNum AND t5.TargetType <> 19 INNER JOIN
OPCH AS T6 ON t5.DocEntry = T6.DocEntry INNER JOIN
OITM AS T7 ON t5.ItemCode = T7.ItemCode INNER JOIN
OLCT AS T8 ON t5.LocCode = T8.Code CROSS JOIN
OITG AS T10
WHERE (T10.ItmsTypCod = (CASE WHEN T7.[QryGroup1] = 'y' THEN 1 WHEN T7.[QryGroup2] = 'y' THEN 2 WHEN T7.[QryGroup3] = 'y' THEN 3 WHEN T7.[QryGroup4] = 'y' THEN
4 WHEN T7.[QryGroup5] = 'y' THEN 5 WHEN T7.[QryGroup6] = 'y' THEN 6 WHEN T7.[QryGroup7] = 'y' THEN 7 WHEN T7.[QryGroup8] = 'y' THEN 8 WHEN T7.[QryGroup9]
= 'y' THEN 9 WHEN T7.[QryGroup60] = 'y' THEN 60 ELSE 0 END)) AND (T6.CardCode <> 'VDD1-100233')
and T6.[DocDate] >=(#date1) and T6.[DocDate] <=(#date2)
Try to do something like this first,
DECLARE #date1 AS DATETIME = '' --your date1
DECLARE #date2 AS DATETIME = '' --your date2
SELECT *
FROM OCRD AS T11
INNER JOIN ORDR AS T0 ON T11.CardCode=T0.CardCode
INNER JOIN RDR1 AS t1 ON T0.DocEntry=t1.DocEntry
LEFT OUTER JOIN POR1 AS t3 ON t3.BaseEntry =t1.DocEntry AND t3.BaseLine=t1.LineNum
AND t3.ItemCode=t1.ItemCode LEFT OUTER JOIN PDN1 AS t4 ON t4.BaseEntry=t3.DocEntry
AND t4.BaseLine=t3.LineNum
AND t4.ItemCode=t3.ItemCode INNER JOIN PCH1 AS t5 ON t5.BaseEntry=t4.DocEntry
AND t5.ItemCode=t4.ItemCode
AND t5.BaseLine=t4.LineNum
AND t5.TargetType<>19 INNER JOIN OPCH AS T6 ON t5.DocEntry=T6.DocEntry INNER
JOIN OITM AS T7 ON t5.ItemCode=T7.ItemCode INNER JOIN OLCT AS T8 ON t5.LocCode
=T8.Code CROSS JOIN OITG AS T10 WHERE (
T10.ItmsTypCod=(
CASE
WHEN T7.[QryGroup1]='y' THEN 1
WHEN T7.[QryGroup2]='y' THEN 2
WHEN T7.[QryGroup3]='y' THEN 3
WHEN T7.[QryGroup4]='y' THEN 4
WHEN T7.[QryGroup5]='y' THEN 5
WHEN T7.[QryGroup6]='y' THEN 6
WHEN T7.[QryGroup7]='y' THEN 7
WHEN T7.[QryGroup8]='y' THEN 8
WHEN T7.[QryGroup9]='y' THEN 9
WHEN T7.[QryGroup60]='y' THEN 60
ELSE 0
END
)
)
AND (T6.[CardCode] <> 'VDD1-100233')
AND T6.[DocDate] >= (#date1)
AND T6.[DocDate] <= (#date2)
If it gives you result then try to add below variables one by one,
T0.DocNum AS 'SO#'
,T6.DocNum AS 'PO#'
,t1.LineTotal AS 'SO Amount'
,T6.DocEntry
,T0.CardName
,T6.U_enduserName
,T11.QryGroup10 AS 'Major A/C Y/N'
,T6.DocEntry AS Expr1
,T6.CardCode
,T6.CardName AS Expr2
,T6.NumAtCard
,T6.DocDate
,t5.ItemCode
,t5.Dscription
,T7.U_itmdes
,t5.Quantity
,t5.LineTotal
,CASE
WHEN T7.[U_itmdes] LIKE '%Desktop%%' THEN T5.[LineTotal]*2.5
ELSE T5.[LineTotal]
END AS 'LineTotal with DTS amt'
,T10.ItmsGrpNam
,T8.Location
,CASE
WHEN T1.[Dscription] LIKE '%Renewal%%' THEN 'Renewal'
ELSE 'Product'
END AS 'Lic Type'
IF (
(
(
(
T10.ItmsGrpNam="ADESK-AEC"
AND T10.ItmsGrpNam="ADESK-AEC-INFRA"
)
AND T1.[Lic TYPE]="Product"
AND T11.QryGroup10="No"
)
)
,[AEC - ENI]
,IF(
(
(
T10.ItmsGrpNam="ADESK-OPEN"
AND T10.ItmsGrpNam="ADESK-HORIZONTAL"
)
AND T1.[Lic TYPE]="Product"
AND T11.QryGroup10="No"
)
,"PSEB"
,IF(
(
(T10.ItmsGrpNam="ADESK-M&E" OR T10.ItmsGrpNam="ADESK-MFG")
AND T1.[Lic TYPE]="Product"
AND T11.QryGroup10="No"
)
,T10.ItmsGrpNam
,IF(
(
(
T10.ItmsGrpNam="ADESK-AEC"
AND T10.ItmsGrpNam="ADESK-AEC-INFRA"
)
AND T1.[Lic TYPE]="Renewal"
AND T11.QryGroup10="No"
)
,"AEC & ENI - Sub Renewal"
,IF(
(
(
T10.ItmsGrpNam="ADESK-OPEN"
AND T10.ItmsGrpNam="ADESK-HORIZONTAL"
)
AND T1.[Lic TYPE]="Renewal"
AND T11.QryGroup10="No"
)
,"PSEB - Sub Renewal"
,IF(
(
(T10.ItmsGrpNam="ADESK-M&E" OR T10.ItmsGrpNam="ADESK-MFG")
AND T1.[Lic TYPE]="Renewal"
AND T11.QryGroup10="No"
)
,"MFG - Sub Renewal"
,"MFG - Sub Renewal"
)
)
)
)
)
)
Note: It will throw error:
Incorrect syntax near ','.
Make it as per your requirement. If is alias then make sure it should work as single variable.
Also I noted you are fetching different variables but you have not put , after AS 'Lic Type'. Check this also.
Below query using CASE ,
DECLARE #date1 AS DATETIME
DECLARE #date2 AS DATETIME
SELECT T0.DocNum AS 'SO#'
,T6.DocNum AS 'PO#'
,t1.LineTotal AS 'SO Amount'
,T6.DocEntry
,T0.CardName
,T6.U_enduserName
,T11.QryGroup10 AS 'Major A/C Y/N'
,T6.DocEntry AS Expr1
,T6.CardCode
,T6.CardName AS Expr2
,T6.NumAtCard
,T6.DocDate
,t5.ItemCode
,t5.Dscription
,T7.U_itmdes
,t5.Quantity
,t5.LineTotal
,CASE
WHEN T7.[U_itmdes] LIKE '%Desktop%%' THEN T5.[LineTotal]*2.5
ELSE T5.[LineTotal]
END AS 'LineTotal with DTS amt'
,T10.ItmsGrpNam
,T8.Location
,CASE
WHEN T1.[Dscription] LIKE '%Renewal%%' THEN 'Renewal'
ELSE 'Product'
END AS 'Lic Type'
,
CASE
WHEN T10.ItmsGrpNam='ADESK-AEC' AND T10.ItmsGrpNam='ADESK-AEC-INFRA' AND T1.[Lic TYPE]='Product' AND T11.QryGroup10='No"' THEN 'AEC - ENI'
WHEN T10.ItmsGrpNam='ADESK-OPEN' AND T10.ItmsGrpNam='ADESK-HORIZONTAL' AND
T1.[Lic TYPE]='Product' AND T11.QryGroup10='No' THEN 'PSEB'
WHEN (T10.ItmsGrpNam='ADESK-M&E' OR T10.ItmsGrpNam='ADESK-MFG') AND T1.[Lic
TYPE]='Product' AND T11.QryGroup10='No' THEN T10.ItmsGrpNam
WHEN T10.ItmsGrpNam='ADESK-AEC' AND T10.ItmsGrpNam='ADESK-AEC-INFRA' AND T1.[Lic
TYPE]='Renewal' AND T11.QryGroup10='No' THEN '"AEC & ENI - Sub Renewal'
WHEN T10.ItmsGrpNam='ADESK-OPE' AND T10.ItmsGrpNam='ADESK-HORIZONTAL' AND
T1.[Lic TYPE]='Renewal' AND T11.QryGroup10='No' THEN
'PSEB - Sub Renewal'
WHEN (T10.ItmsGrpNam='ADESK-M&E' OR T10.ItmsGrpNam='ADESK-MFG') AND [T1.Lic
TYPE]='Renewal' AND T11.QryGroup10='No' THEN 'MFG - Sub Renewal'
ELSE 'MFG - Sub Renewal'
END
FROM OCRD AS T11
INNER JOIN ORDR AS T0 ON T11.CardCode=T0.CardCode
INNER JOIN RDR1 AS t1 ON T0.DocEntry=t1.DocEntry
LEFT OUTER JOIN POR1 AS t3 ON t3.BaseEntry =t1.DocEntry AND t3.BaseLine=t1.LineNum
AND t3.ItemCode=t1.ItemCode LEFT OUTER JOIN PDN1 AS t4 ON t4.BaseEntry=t3.DocEntry
AND t4.BaseLine=t3.LineNum
AND t4.ItemCode=t3.ItemCode INNER JOIN PCH1 AS t5 ON t5.BaseEntry=t4.DocEntry
AND t5.ItemCode=t4.ItemCode
AND t5.BaseLine=t4.LineNum
AND t5.TargetType<>19 INNER JOIN OPCH AS T6 ON t5.DocEntry=T6.DocEntry INNER
JOIN OITM AS T7 ON t5.ItemCode=T7.ItemCode INNER JOIN OLCT AS T8 ON t5.LocCode
=T8.Code CROSS JOIN OITG AS T10 WHERE (
T10.ItmsTypCod=(
CASE
WHEN T7.[QryGroup1]='y' THEN 1
WHEN T7.[QryGroup2]='y' THEN 2
WHEN T7.[QryGroup3]='y' THEN 3
WHEN T7.[QryGroup4]='y' THEN 4
WHEN T7.[QryGroup5]='y' THEN 5
WHEN T7.[QryGroup6]='y' THEN 6
WHEN T7.[QryGroup7]='y' THEN 7
WHEN T7.[QryGroup8]='y' THEN 8
WHEN T7.[QryGroup9]='y' THEN 9
WHEN T7.[QryGroup60]='y' THEN 60
ELSE 0
END
)
)
AND (T6.[CardCode] <> 'VDD1-100233')
AND T6.[DocDate] >= (#date1)
AND T6.[DocDate] <= (#date2)
You have the following in several places in select part:
T1.Lic Type="Product"
You have to delimit that column. Change to this:
T1.[Lic Type]="Product"
It is a pain to gebug so many IIF operators. Change to CASE expressions. You will gain both in readability and standardization of your code. Also change double quotes to single quotes.
case when T10.ItmsGrpNam='ADESK-AEC' and T10.ItmsGrpNam='ADESK-AEC-INFRA' and T1.[Lic Type]='Product' and T11.QryGroup10='No"' then 'AEC - ENI'
when T10.ItmsGrpNam='ADESK-OPEN' and T10.ItmsGrpNam='ADESK-HORIZONTAL' and T1.[Lic Type]='Product' and T11.QryGroup10='No' then 'PSEB'
when (T10.ItmsGrpNam='ADESK-M&E' or T10.ItmsGrpNam='ADESK-MFG') and T1.[Lic Type]='Product' and T11.QryGroup10='No' then T10.ItmsGrpNam
when T10.ItmsGrpNam='ADESK-AEC' and T10.ItmsGrpNam='ADESK-AEC-INFRA' and T1.[Lic Type]='Renewal' and T11.QryGroup10='No' then'"AEC & ENI - Sub Renewal'
when T10.ItmsGrpNam='ADESK-OPE' and T10.ItmsGrpNam='ADESK-HORIZONTAL' and T1.[Lic Type]='Renewal' and T11.QryGroup10='No' then 'PSEB - Sub Renewal'
when (T10.ItmsGrpNam='ADESK-M&E' or T10.ItmsGrpNam='ADESK-MFG') and T1.[Lic Type]='Renewal' and T11.QryGroup10='No' then 'MFG - Sub Renewal'
else 'MFG - Sub Renewal' end
EDIT:
Here is the full statement:
DECLARE #date1 DATETIME, #date2 DATETIME
SELECT T0.DocNum AS 'SO#' ,
T6.DocNum AS 'PO#' ,
t1.LineTotal AS 'SO Amount' ,
T6.DocEntry ,
T0.CardName ,
T6.U_enduserName ,
T11.QryGroup10 AS 'Major A/C Y/N' ,
T6.DocEntry AS Expr1 ,
T6.CardCode ,
T6.CardName AS Expr2 ,
T6.NumAtCard ,
T6.DocDate ,
t5.ItemCode ,
t5.Dscription ,
T7.U_itmdes ,
t5.Quantity ,
t5.LineTotal ,
CASE WHEN T7.[U_itmdes] LIKE '%Desktop%%' THEN T5.[LineTotal] * 2.5
ELSE T5.[LineTotal]
END AS 'LineTotal with DTS amt' ,
T10.ItmsGrpNam ,
T8.Location ,
CASE WHEN T1.[Dscription] LIKE '%Renewal%%' THEN 'Renewal'
ELSE 'Product'
END AS 'Lic Type' ,
CASE WHEN T10.ItmsGrpNam = 'ADESK-AEC'
AND T10.ItmsGrpNam = 'ADESK-AEC-INFRA'
AND T1.[Lic Type] = 'Product'
AND T11.QryGroup10 = 'No"' THEN 'AEC - ENI'
WHEN T10.ItmsGrpNam = 'ADESK-OPEN'
AND T10.ItmsGrpNam = 'ADESK-HORIZONTAL'
AND T1.[Lic Type] = 'Product'
AND T11.QryGroup10 = 'No' THEN 'PSEB'
WHEN ( T10.ItmsGrpNam = 'ADESK-M&E'
OR T10.ItmsGrpNam = 'ADESK-MFG'
)
AND T1.[Lic Type] = 'Product'
AND T11.QryGroup10 = 'No' THEN T10.ItmsGrpNam
WHEN T10.ItmsGrpNam = 'ADESK-AEC'
AND T10.ItmsGrpNam = 'ADESK-AEC-INFRA'
AND T1.[Lic Type] = 'Renewal'
AND T11.QryGroup10 = 'No' THEN '"AEC & ENI - Sub Renewal'
WHEN T10.ItmsGrpNam = 'ADESK-OPE'
AND T10.ItmsGrpNam = 'ADESK-HORIZONTAL'
AND T1.[Lic Type] = 'Renewal'
AND T11.QryGroup10 = 'No' THEN 'PSEB - Sub Renewal'
WHEN ( T10.ItmsGrpNam = 'ADESK-M&E'
OR T10.ItmsGrpNam = 'ADESK-MFG'
)
AND T1.[Lic Type] = 'Renewal'
AND T11.QryGroup10 = 'No' THEN 'MFG - Sub Renewal'
ELSE 'MFG - Sub Renewal'
END
FROM OCRD AS T11
INNER JOIN ORDR AS T0 ON T11.CardCode = T0.CardCode
INNER JOIN RDR1 AS t1 ON T0.DocEntry = t1.DocEntry
LEFT OUTER JOIN POR1 AS t3 ON t3.BaseEntry = t1.DocEntry
AND t3.BaseLine = t1.LineNum
AND t3.ItemCode = t1.ItemCode
LEFT OUTER JOIN PDN1 AS t4 ON t4.BaseEntry = t3.DocEntry
AND t4.BaseLine = t3.LineNum
AND t4.ItemCode = t3.ItemCode
INNER JOIN PCH1 AS t5 ON t5.BaseEntry = t4.DocEntry
AND t5.ItemCode = t4.ItemCode
AND t5.BaseLine = t4.LineNum
AND t5.TargetType <> 19
INNER JOIN OPCH AS T6 ON t5.DocEntry = T6.DocEntry
INNER JOIN OITM AS T7 ON t5.ItemCode = T7.ItemCode
INNER JOIN OLCT AS T8 ON t5.LocCode = T8.Code
CROSS JOIN OITG AS T10
WHERE ( T10.ItmsTypCod = ( CASE WHEN T7.[QryGroup1] = 'y' THEN 1
WHEN T7.[QryGroup2] = 'y' THEN 2
WHEN T7.[QryGroup3] = 'y' THEN 3
WHEN T7.[QryGroup4] = 'y' THEN 4
WHEN T7.[QryGroup5] = 'y' THEN 5
WHEN T7.[QryGroup6] = 'y' THEN 6
WHEN T7.[QryGroup7] = 'y' THEN 7
WHEN T7.[QryGroup8] = 'y' THEN 8
WHEN T7.[QryGroup9] = 'y' THEN 9
WHEN T7.[QryGroup60] = 'y' THEN 60
ELSE 0
END ) )
AND ( T6.CardCode <> 'VDD1-100233' )
AND T6.[DocDate] >= ( #date1 )
AND T6.[DocDate] <= ( #date2 )

SQL Select within Sub Query

Hi My query is as follows, and contains a subquery within it:
ALTER PROCEDURE [dbo].[POBalance] #PONumber NVARCHAR(50)
AS
BEGIN
SELECT CASE
WHEN X.STATUS = 'False'
THEN ( SELECT A.Description
,C.qty AS POqty
,B.Qty AS PDQty
,CASE
WHEN A.partialflag = 'false'
THEN '0'
ELSE A.qty
END AS Balance
,A.Unit
,A.Unitprice
,A.Partialflag
FROM tblPOdetails AS A
INNER JOIN tblPDdetails AS B ON A.id = B.id
INNER JOIN tblpodetailshistory AS C ON A.id = C.id
WHERE A.PONo = #PONumber
)
ELSE ( SELECT A.Description
,C.qty AS POqty
,B.Qty AS PDQty
,C.qty AS Balance
,A.Unit
,A.Unitprice
,A.Partialflag
FROM tblPOdetails AS A
INNER JOIN tblPDdetails AS B ON A.id = B.id
INNER JOIN tblpodetailshistory AS C ON A.id = C.id
WHERE A.PONo = #PONumber)
END
FROM tblPOHeader AS X
WHERE x.PONo = #PONumber
END
The error i get is :
Only one expression can be specified in the select list when the subquery is not
introduced with EXISTS.
What is wrong with my query..it seems my sub query is OK.
THanks in Advance
You can not select table in case clausule. You can do it just like that (I didn't test it):
SELECT A.Description
,C.qty AS POqty
,B.Qty AS PDQty
,CASE
WHEN A.partialflag = 'false'
THEN '0'
ELSE A.qty
END AS Balance
,A.Unit
,A.Unitprice
,A.Partialflag
FROM tblPOdetails AS A
INNER JOIN tblPDdetails AS B ON A.id = B.id
INNER JOIN tblpodetailshistory AS C ON A.id = C.id
INNER JOIN tblPOHeader X ON x.PONo = A.PONo
WHERE A.PONo = #PONumber and X.STATUS = 'False'
UNION ALL
SELECT A.Description
,C.qty AS POqty
,B.Qty AS PDQty
,C.qty AS Balance
,A.Unit
,A.Unitprice
,A.Partialflag
FROM tblPOdetails AS A
INNER JOIN tblPDdetails AS B ON A.id = B.id
INNER JOIN tblpodetailshistory AS C ON A.id = C.id
INNER JOIN tblPOHeader X ON x.PONo = A.PONo
WHERE A.PONo = #PONumber and X.STATUS <> 'False'
But I think tah X.STATUS is bit - if yes you should do it just like that:
SELECT A.Description
,C.qty AS POqty
,B.Qty AS PDQty
,CASE
WHEN A.partialflag = 'false'
THEN '0'
ELSE A.qty
END AS Balance
,A.Unit
,A.Unitprice
,A.Partialflag
FROM tblPOdetails AS A
INNER JOIN tblPDdetails AS B ON A.id = B.id
INNER JOIN tblpodetailshistory AS C ON A.id = C.id
INNER JOIN tblPOHeader X ON x.PONo = A.PONo
WHERE A.PONo = #PONumber and X.STATUS = 0
UNION ALL
SELECT A.Description
,C.qty AS POqty
,B.Qty AS PDQty
,C.qty AS Balance
,A.Unit
,A.Unitprice
,A.Partialflag
FROM tblPOdetails AS A
INNER JOIN tblPDdetails AS B ON A.id = B.id
INNER JOIN tblpodetailshistory AS C ON A.id = C.id
INNER JOIN tblPOHeader X ON x.PONo = A.PONo
WHERE A.PONo = #PONumber and X.STATUS <> 0
Are you actually looking for this?
ALTER PROCEDURE [dbo].[POBalance] #PONumber NVARCHAR(50)
AS
BEGIN
DECLARE #Status NVARCHAR(MAX)
SELECT #Status = X.STATUS
FROM tblPOHeader AS X WHEREx.PONo = #PONumber
IF #Status = 'False'
BEGIN
SELECT A.Description
,C.qty AS POqty
,B.Qty AS PDQty
,CASE
WHEN A.partialflag = 'false'
THEN '0'
ELSE A.qty
END AS Balance
,A.Unit
,A.Unitprice
,A.Partialflag
FROM tblPOdetails AS A
INNER JOIN tblPDdetails AS B ON A.id = B.id
INNER JOIN tblpodetailshistory AS C ON A.id = C.id
WHERE A.PONo = #PONumber
END
ELSE
BEGIN
SELECT A.Description
,C.qty AS POqty
,B.Qty AS PDQty
,C.qty AS Balance
,A.Unit
,A.Unitprice
,A.Partialflag
FROM tblPOdetails AS A
INNER JOIN tblPDdetails AS B ON A.id = B.id
INNER JOIN tblpodetailshistory AS C ON A.id = C.id
WHERE A.PONo = #PONumber
END
END
This code will store and then check the value of #Status and based on if the value is False or not then it will return the result set of one of the queries.
You cannot select multiple fields for one expression.Your alias makes it more visible.You select more than one value and give only one alias name!!
Please refer this
Only One Expression in case
And this one too
Another one here
When
select * from tblPOHeader where PONo = #PONumber
returns only one row you can do something like that
declare #STATUS nvarchar(200) = ( select STATUS from tblPOHeader where PONo = #PONumber)
if #STATUS = 'False'
SELECT A.Description
,C.qty AS POqty
,B.Qty AS PDQty
,CASE
WHEN A.partialflag = 'false'
THEN '0'
ELSE A.qty
END AS Balance
,A.Unit
,A.Unitprice
,A.Partialflag
FROM tblPOdetails AS A
INNER JOIN tblPDdetails AS B ON A.id = B.id
INNER JOIN tblpodetailshistory AS C ON A.id = C.id
WHERE A.PONo = #PONumber
ELSE
SELECT A.Description
,C.qty AS POqty
,B.Qty AS PDQty
,C.qty AS Balance
,A.Unit
,A.Unitprice
,A.Partialflag
FROM tblPOdetails AS A
INNER JOIN tblPDdetails AS B ON A.id = B.id
INNER JOIN tblpodetailshistory AS C ON A.id = C.id
WHERE A.PONo = #PONumber

There is already an object named '##tempTable' in the database

When executing the query below, I am receiving the error: There is already an object named '##tempTable' in the database. I am using a temporary table to insert the results and do other things not important to the question, but I need this if statement because there are a few minor differences in the queries and I don't know how to consolidate into 1 query. The error occurs in the else statement SELECT... INTO ##tempTable because I already perform this operation in the if. Is there any work around to this besides getting rid of the if else statement and consolidatin into one query?
IF #isQuintile = 1
BEGIN
SELECT MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID, 0 AS 'fkDemographicCodeID', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_0', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) AS 'Count_0', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '0') AS 'BandID_0', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_1', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) AS 'Count_1', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '1') AS 'BandID_1'
INTO ##tempTable FROM StudentScores_Subject
INNER JOIN StudentTests ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
INNER JOIN TestInstances ON TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
INNER JOIN CAHSEE_TestPeriods ON CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
INNER JOIN PerformanceLevelReportBands bands ON bands.fkPerformanceLevelReportID = #intPerfLevelReportId
LEFT JOIN MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND cutScores.fkGradeID = #intGradeId
AND cutScores.fkTestSubjectID IN (SELECT id FROM #tempSubs)
INNER JOIN PerfLevelReportBandComponents bandComponents ON bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND((bandComponents.ScoreValue = StudentScores_Subject.ScoreValue)
OR ((CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN bandComponents.minScore and bandComponents.maxScore)
OR (CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN cutScores.minScore and cutScores.maxScore)))
RIGHT JOIN MM_SchoolYears ON MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
WHERE MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(#strYearIds, N','))
AND bands.fkPerformanceLevelReportID = #intPerfLevelReportId
AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM #tempTests)
AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM #tempSubs)
GROUP BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
ORDER BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
END
ELSE
BEGIN
SELECT MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID, 0 AS 'fkDemographicCodeID', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_0', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) AS 'Count_0', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '0') AS 'BandID_0', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_1', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) AS 'Count_1', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '1') AS 'BandID_1'
INTO ##tempTable FROM StudentScores_Subject
INNER JOIN StudentTests ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
INNER JOIN TestInstances ON TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
INNER JOIN CAHSEE_TestPeriods ON CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
INNER JOIN PerformanceLevelReportBands bands ON bands.fkPerformanceLevelReportID = #intPerfLevelReportId
LEFT JOIN MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND cutScores.fkGradeID = #intGradeId
AND cutScores.fkTestSubjectID IN (SELECT id FROM #tempSubs)
INNER JOIN PerfLevelReportBandComponents bandComponents ON bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND((bandComponents.ScoreValue = StudentScores_Subject.ScoreValue))
RIGHT JOIN MM_SchoolYears ON MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
WHERE MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(#strYearIds, N','))
AND bands.fkPerformanceLevelReportID = #intPerfLevelReportId
AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM #tempTests)
AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM #tempSubs)
GROUP BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
ORDER BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
END
EDIT Should have specified, but the reason I am selecting INTO is because the select is created dynamically so I don't know how many columns there will be. In my example I just showed what it would look like if there was only count, percent, and band 0 and 1 selected.
You need to Check Some thing like this Before Creating Temporary Tables
if OBJECT_ID(''tempdb..##tempTable) is not null
drop table ##tempTable
Then Your
SELECT * INTO ##tempTable......
##tempTable(Global temporary table) and #temptable(local Temporary table)
See the difference..
Local and global temporary tables in SQL Server
create table #tempTable(declare the columns here..)
IF #isQuintile = 1
BEGIN
SELECT MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID, 0 AS 'fkDemographicCodeID', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_0', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) AS 'Count_0', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '0') AS 'BandID_0', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_1', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) AS 'Count_1', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '1') AS 'BandID_1'
INTO #tempTable FROM StudentScores_Subject
INNER JOIN StudentTests ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
INNER JOIN TestInstances ON TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
INNER JOIN CAHSEE_TestPeriods ON CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
INNER JOIN PerformanceLevelReportBands bands ON bands.fkPerformanceLevelReportID = #intPerfLevelReportId
LEFT JOIN MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND cutScores.fkGradeID = #intGradeId
AND cutScores.fkTestSubjectID IN (SELECT id FROM #tempSubs)
INNER JOIN PerfLevelReportBandComponents bandComponents ON bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND((bandComponents.ScoreValue = StudentScores_Subject.ScoreValue)
OR ((CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN bandComponents.minScore and bandComponents.maxScore)
OR (CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN cutScores.minScore and cutScores.maxScore)))
RIGHT JOIN MM_SchoolYears ON MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
WHERE MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(#strYearIds, N','))
AND bands.fkPerformanceLevelReportID = #intPerfLevelReportId
AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM #tempTests)
AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM #tempSubs)
GROUP BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
ORDER BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
END
ELSE
BEGIN
SELECT MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID, 0 AS 'fkDemographicCodeID', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_0', SUM(CASE WHEN bands.StackPosition = '0' THEN 1 ELSE 0 END) AS 'Count_0', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '0') AS 'BandID_0', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS 'Percent_1', SUM(CASE WHEN bands.StackPosition = '1' THEN 1 ELSE 0 END) AS 'Count_1', (SELECT bb.pkPerformanceLevelReportBandID FROM PerformanceLevelReportBands bb WHERE bb.fkPerformanceLevelReportID = '6' AND bb.StackPosition = '1') AS 'BandID_1'
INTO #tempTable FROM StudentScores_Subject
INNER JOIN StudentTests ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
INNER JOIN TestInstances ON TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
INNER JOIN CAHSEE_TestPeriods ON CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
INNER JOIN PerformanceLevelReportBands bands ON bands.fkPerformanceLevelReportID = #intPerfLevelReportId
LEFT JOIN MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND cutScores.fkGradeID = #intGradeId
AND cutScores.fkTestSubjectID IN (SELECT id FROM #tempSubs)
INNER JOIN PerfLevelReportBandComponents bandComponents ON bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND((bandComponents.ScoreValue = StudentScores_Subject.ScoreValue))
RIGHT JOIN MM_SchoolYears ON MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
WHERE MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(#strYearIds, N','))
AND bands.fkPerformanceLevelReportID = #intPerfLevelReportId
AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM #tempTests)
AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM #tempSubs)
GROUP BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
ORDER BY MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
END
You don't need to use SELECT INTO...
Just create the temp table (local or global) first and the do an INSERT INTO...SELECT:
IF (OBJECT_ID(N'tempdb..#tempTable') IS NOT NULL)
BEGIN
DROP TABLE #tempTable;
END;
CREATE TABLE #tempTable (
pkSchoolYearID datatype,
pkTestInstanceID datatype,
fkTest_SubjectID datatype,
fkDemographicCodeID INT
Percent_0 datatype
Count_0 datatype,
BandID_0 datatype,
Percent_1 datatype,
Count_1 datatype,
BandID_1 datatype
);
IF (#isQuintile = 1)
BEGIN
INSERT INTO #tempTable -- this has been added!!
SELECT MM_SchoolYears.pkSchoolYearID, TestInstances.pkTestInstanceID, ...
-- INTO ##tempTable -- this has been removed!!
INNER JOIN StudentTests
ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
...

Resources