Error comparing the output of datepart to an integer - tsql

I have a query that i have been tinkering with to use as a source for a report.
For some odd reason when i try to compare the output of datepart(dw,GetDate()) to an integer (2 for Monday) it gives me an error telling me incorrect syntax. i then started looking into why i couldn't compare two integers in an iif statement and... i have found absolutely no answers.
here is the full code (i went back and forth on how to do this, this is this iterations attempt)
DECLARE #dp integer,#d integer
set #dp =DATEpart(dw,GETDATE())
set #d = 2
SELECT TOP 100 PERCENT CUST_ORDER_LINE.PRODUCT_CODE
,CUSTOMER_ORDER.ID
,CUSTOMER_ORDER.CUSTOMER_ID
,CUST_ORDER_LINE.PART_ID
,CUST_ORDER_LINE.MISC_REFERENCE
,CUST_ORDER_LINE.COMMODITY_CODE
,CUSTOMER_ORDER.SALESREP_ID
,CUSTOMER_ORDER.TERRITORY
,CUST_ORDER_LINE.ORDER_QTY * CUST_ORDER_LINE.UNIT_PRICE AS Amount
,CUSTOMER_ORDER.ORDER_DATE
FROM CUST_ORDER_LINE
INNER JOIN CUSTOMER_ORDER ON CUST_ORDER_LINE.CUST_ORDER_ID = CUSTOMER_ORDER.ID
WHERE (
iif(#dp = #d,CUSTOMER_ORDER.ORDER_DATE BETWEEN ( dateadd(day, datediff(day, 0, getdate()), 0) - 3) AND ( dateadd(day, datediff(day, 0, getdate()),0))),
CUSTOMER_ORDER.ORDER_DATE BETWEEN ( dateadd(day, datediff(day, 0, getdate()), 0) - 1)) AND ( dateadd(day, datediff(day, 0, getdate()), + 1))))
)
ORDER BY CUSTOMER_ORDER.ORDER_DATE DESC
The point of this query is to pull data from yesterday, and Friday if it is Monday.
EDIT: error code Msg 170, Level 15, State 1, Line 19
Line 19: Incorrect syntax near '='.

IIF is in 2012. You can try using CASE instead.
DECLARE #dp integer,#d integer
set #dp =DATEpart(dw,GETDATE())
set #d = 2
SELECT TOP 100 PERCENT CUST_ORDER_LINE.PRODUCT_CODE
,CUSTOMER_ORDER.ID
,CUSTOMER_ORDER.CUSTOMER_ID
,CUST_ORDER_LINE.PART_ID
,CUST_ORDER_LINE.MISC_REFERENCE
,CUST_ORDER_LINE.COMMODITY_CODE
,CUSTOMER_ORDER.SALESREP_ID
,CUSTOMER_ORDER.TERRITORY
,CUST_ORDER_LINE.ORDER_QTY * CUST_ORDER_LINE.UNIT_PRICE AS Amount
,CUSTOMER_ORDER.ORDER_DATE
FROM CUST_ORDER_LINE
INNER JOIN CUSTOMER_ORDER ON CUST_ORDER_LINE.CUST_ORDER_ID = CUSTOMER_ORDER.ID
WHERE
CUSTOMER_ORDER.ORDER_DATE BETWEEN CASE
WHEN #dp = #d THEN ( dateadd(day, datediff(day, 0, getdate()), 0) - 3)
ELSE ( dateadd(day, datediff(day, 0, getdate()), 0) - 1)
END
AND CASE
WHEN #dp = #d THEN ( dateadd(day, datediff(day, 0, getdate()),0))
ELSE ( dateadd(day, datediff(day, 0, getdate()), + 1))
END
ORDER BY CUSTOMER_ORDER.ORDER_DATE DESC

Related

Multiple cases that allows different conversion of column that is being checked in WHERE CASE WHEN clause

SELECT Clmn
FROM Tbl T
INNER JOIN SomeotherTbl
WHERE CONVERT(varchar(10), T.[Date], 120) =
CASE #SortOrder
WHEN '1' THEN CONVERT(varchar(10), GETDATE(), 120)
WHEN '2' THEN CONVERT(varchar(7), GETDATE(), 120)
WHEN '3' THEN CONVERT(varchar(4), GETDATE(), 120)
END
So i have a Date column that i converted to varchar , but i would like to convert it to different length according to #SortOrder , what's the best solution ?
Use Like instead of =:
WHERE CONVERT(varchar(10),D.[Date],120) LIKE
CASE #SortOrder
WHEN '1' THEN CONVERT(varchar(10),GETDATE(),120)
WHEN '2' THEN CONVERT(varchar(7),GETDATE(),120) +'%'
WHEN '3' THEN CONVERT(varchar(4),GETDATE(),120) +'%'
END
Another option (without using case) is this:
WHERE (#SortOrder > '3' OR YEAR(D.[Date]) = YEAR(GETDATE()))
AND (#SortOrder > '2' OR MONTH(D.[Date]) = MONTH(GETDATE()))
AND (#SortOrder > '1' OR DAY(D.[Date]) = DAY(GETDATE()))
And yet another option, that will work for versions 2012 or higher, and is a little more complicated, but if you have an index on the [Date] column will allow SQL Server to use it:
DECLARE #Date date = GETDATE()
DECLARE #ThisMonth date = DATEFROMPARTS(YEAR(#Date), MONTH(#Date), 1)
DECLARE #ThisYear date = DATEFROMPARTS(YEAR(#Date), 1, 1)
SELECT ...
FROM ...
WHERE
(#SortOrder = '1' AND D.[Date] = #Date)
OR (#SortOrder = '2' AND D.[Date] >= #ThisMonth AND D.[Date] < DATEADD(MONTH, 1, #ThisMonth))
OR (#SortOrder = '3' AND D.[Date] >= #ThisYear AND D.[Date] < DATEADD(YEAR, 1, #ThisYear))
You can see a live demo on rextester.
If you want to compare year, month, and day there are better ways
select CONVERT(varchar(10), GETDATE(), 120), CONVERT(varchar(7), GETDATE(), 120), CONVERT(varchar(4), GETDATE(), 120)
, DATEPART(year, getdate()), DATEPART(month, getdate()), DATEPART(day, getdate())
2018-02-22 2018-02 2018 2018 2 22

Build the calendar table for current year including weeknum divided to semester

for the below query i need divide the semesters starting from 1 to 26 .. first semester as 1 to 26 weeks and first semester should start from again 1 to 26
Any help is greating appreciated
DECLARE #StartDate DATETIME
DECLARE #CutoffDate DATETIME
SET #StartDate = Dateadd(yy, Datediff(yy, 0, Getdate()), 0)
SET #CutoffDate = Dateadd(yy, Datediff(yy, 0, Getdate()) + 1, -1)
SELECT day,
[week nu],
semester,
[semester week nu]
INTO #currentdates
FROM (SELECT Day = Dateadd(day, rn - 1, #StartDate),
Datepart(week, Dateadd(day, rn - 1, #StartDate)) [Week nu],
CASE
WHEN Month(Dateadd(day, rn - 1, #StartDate)) <= 6 THEN
'First Semester'
ELSE 'Second Semester'
END AS Semester,
Datepart(week, Dateadd(day, rn - 1, #StartDate)) AS
[Semester Week nu]
FROM (SELECT TOP (Datediff(day, #StartDate, #CutoffDate)) rn =
Row_number()
OVER (
ORDER BY s1.[object_id])
FROM sys.all_objects AS s1
CROSS JOIN sys.all_objects AS s2
ORDER BY s1.[object_id]) AS x) AS y;
I've got a couple of changes, first, you need to add 1 to your last datediff, your last date was December 30, not 31!
Second of all, I just get the date and week number in the first subselect, and then use these ine case statements for the select
The semester number is if week nu<=26,
The semester week nu is week nu if week nu<=26 else wwek nu -26
DECLARE #StartDate datetime DECLARE #CutoffDate datetime
SET #StartDate = DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
SET #CutoffDate = DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1)
SELECT DAY,
[Week nu],
case when [Week nu]<=26 then 'First Semester' Else 'Second Semester' end Semester,
case when [Week nu]<=26 then [Week nu] Else [Week nu]-26 end[Semester Week nu]
INTO #currentDates
FROM
(SELECT DAY = DATEADD(DAY, rn - 1, #StartDate),
DATEPART(WEEK,DATEADD(DAY, rn - 1, #StartDate)) [Week nu]
FROM
(SELECT TOP (DATEDIFF(DAY, #StartDate, #CutoffDate)+1) rn = ROW_NUMBER() OVER (ORDER BY s1.[object_id])
FROM sys.all_objects AS s1
CROSS JOIN sys.all_objects AS s2
ORDER BY s1.[object_id]) AS x) AS y;

SQL Server 2012: Round to NEAREST(!) start of month (in timestamp format) from a timestamp column)

I need to round to NEAREST start of month (in timestamp format) from a timestamp column.
How do one accomplish this?
Examples:
TimestampColumn A: Rounded to these values
2012-01-07 18:18:29.923 2012-01-01 00:00:00.000
2012-01-14 12:58:13.122 2012-01-01 00:00:00.000
2012-06-09 17:10:30.787 2012-06-01 00:00:00.000
2012-05-31 09:29:43.870 2012-06-01 00:00:00.000
2012-10-22 12:09:47.067 2012-11-01 00:00:00.000
2012-10-15 04:35:11.013 2012-10-01 00:00:00.000
Consider converting to date first
DECLARE #d DATETIME
set #d = CONVERT(DATE, '2012-02-14 12:58:13.122')
SET #d = DATEADD(DAY, 1-datepart(day, #d), #d)
SELECT #d
Here is one way to do it - just subtract all the parts of the date which you don't care about:
DECLARE #d DATETIME
set #d = '2012-02-14 12:58:13.122'
SET #d = DATEADD(DAY, 1-datepart(day, #d), #d)
SET #d = DATEADD(hour, -datepart(hour, #d), #d)
SET #d = DATEADD(minute, -datepart(minute, #d), #d)
SET #d = DATEADD(second, -datepart(second, #d), #d)
SET #d = DATEADD(millisecond, -datepart(millisecond, #d), #d)
SELECT #d
Calculate the length of the applicable month in seconds and then decide whether you are past the middle of the month. Go forward or back as needed.
declare #Foo as DateTime = '2012-10-15 12:35:11.013'
select
DateAdd( month, DateDiff( m, 0, #Foo ), 0 ) as 'Year/Month',
DateDiff( s, DateAdd( month, DateDiff( m, 0, #Foo ), 0), #Foo ) as 'Seconds Into Month',
DateDiff( s, DateAdd( month, DateDiff( m, 0, #Foo ), 0 ), DateAdd( month, DateDiff( m, 0, #Foo ) + 1, 0 ) ) as 'Seconds In Month',
DateDiff( s, DateAdd( month, DateDiff( m, 0, #Foo ), 0 ), DateAdd( month, DateDiff( m, 0, #Foo ) + 1, 0 ) ) / 2 as 'Seconds In Half Month',
DateAdd( month, DateDiff( m, 0, #Foo ) + Round( 1.0 * DateDiff( s, DateAdd( month, DateDiff( m, 0, #Foo ), 0), #Foo ) / DateDiff( s, DateAdd( month, DateDiff( m, 0, #Foo ), 0 ), DateAdd( month, DateDiff( m, 0, #Foo ) + 1, 0 ) ), 0 ), 0 ) as 'Rounded Date'
Thanks for contributing. But I'm going for this one; its good enough.
SELECT CASE
WHEN DATEDIFF(DAY, GETDATE(), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0)) >
ABS(DATEDIFF(DAY, GETDATE(), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)))
THEN DATEADD(dd, datediff(dd, 0, DATEADD(DAY, DATEDIFF(DAY, GETDATE(), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)), GETDATE() ) )+0, 0)
ELSE dateadd(dd, datediff(dd, 0, DATEADD(DAY, DATEDIFF(DAY, GETDATE(), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0)), GETDATE() ) )+0, 0)
END
Here is an example. You have 5 fields: the date you want to convert, the converted date as you wanted, the first day of the month, the last day of the month, and the first day of the next month.
Just choose what you need in it:
SELECT
BED_Meeting_When,
CASE WHEN DAY(BED_Meeting_When) < 15 THEN (DATEADD(DAY, (-DAY(BED_Meeting_When) + 1), BED_Meeting_When)) ELSE DATEADD(DAY, (-DAY(BED_Meeting_When) + 1), DATEADD(MONTH, 1, BED_Meeting_When)) END,
DATEADD(DAY, (-DAY(BED_Meeting_When) + 1), BED_Meeting_When) AS 'Arrondi au premier du mois',
DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, BED_Meeting_When) + 1, 0)) AS 'Arrondi au dernier du mois',
DATEADD(DAY, (-DAY(BED_Meeting_When) + 1), DATEADD(MONTH, 1, BED_Meeting_When)) AS 'Arrondi au premier du mois suivant',
BEMR_Titre
FROM bpri_entretien_detail
INNER JOIN bpri_entretien_motif ON (BED_BEMR_Idx = BEMR_Idx)
Hi I know this is late to the party a little simple offering can never offend I hope
Creating a mini temp table I pop'd the dates offered in the original post
and then selected from it as below
create table #DT(
TS_A datetime, TS_B datetime)
insert into #DT (ts_a) values ('2012-01-07 18:18:29.923'),
('2012-01-14 12:58:13.122'),
('2012-06-09 17:10:30.787'),
('2012-05-31 09:29:43.870'),
('2012-10-22 12:09:47.067'),
('2012-10-15 04:35:11.013')
select TS_A, DATEADD(MONTH, DATEDIFF(MONTH, 0,ts_a), 0) TS_B from #DT
Results - I hope this is clear
RESULTS
Amazing how times they are a changing :-)
TX
I hope this turns out alright haven't posted any where for over a decade

tsql dynamic where

I'm struggling with this procedure.
If its Monday thru Thursday I want everything 90 days ahead;
SELECT
PR.ClientID
,PR.NewDealEndDate
INTO
#OriginalRenewalDetails
FROM
Shiva.dbo.ProductRemortgage PR WITH (NOLOCK)
LEFT JOIN Shiva.dbo.ClientLead AS CL WITH (NOLOCK)
ON CONVERT(VARCHAR(50), CL.OriginatorReferenceID) = CONVERT(VARCHAR(50), PR.ClientID)
WHERE -- 90 days from now.
PR.NewDealEndDate = DATEADD(dd, 90, DATEDIFF(dd, 00, GETDATE()))
AND CL.ClientID IS NULL
However if it is a Sunday I want the following changed in the Where clause. So that I get Friday and Saturdays results too.
WHERE -- 90 days from now.
PR.NewDealEndDate BETWEEN DATEADD(dd, 88, DATEDIFF(dd, 00, GETDATE())) AND DATEADD(dd, 90, DATEDIFF(dd, 00, GETDATE()))
AND CL.ClientID IS NULL
I can't find an efficient way of doing this. Any help appreciated.
Use IF.
pseudo:
if day = sunday
begin
select with 88
end
else
begin
select with 90
end
OR change the WHERE clauses to something like:
WHERE (PR.NewDealEndDate = DATEADD(dd, 90, DATEDIFF(dd, 00, GETDATE()))
AND CL.ClientID IS NULL AND Datepart(weekday, getdate()) <> 1)
OR
(PR.NewDealEndDate BETWEEN DATEADD(dd, 88, DATEDIFF(dd, 00, GETDATE()))
AND DATEADD(dd, 90, DATEDIFF(dd, 00, GETDATE()))
AND CL.ClientID IS NULL
AND Datepart(weekday, getdate()) = 1)
No need for dynamic SQL or two separate queries here. Replacing the **DAY = SUNDAY** part with whatever logic you're currently using to determine the day is Sunday:
WHERE PR.NewDealEndDate BETWEEN DATEADD(DAY,
CASE WHEN **DAY = SUNDAY** THEN 88 ELSE 90 END,
DATEDIFF(DAY, 0, GETDATE())) AND DATEADD(DAY, 90, DATEDIFF(dd, 0, GETDATE()))
AND CL.ClientID IS NULL;
You could also calculate the range beforehand, e.g.
DECLARE #start SMALLDATETIME, #end SMALLDATETIME;
SET #end = DATEADD(DAY, 90, DATEDIFF(DAY, 0, GETDATE()));
SET #start = CASE WHEN **DAY = SUNDAY** THEN DATEADD(DAY, -2, #end) ELSE #end END;
WHERE PR.NewDealEndDate BETWEEN #start END #end
AND CL.ClientID IS NULL;
You could do the following:
SELECT PR.ClientID
, PR.NewDealEndDate
INTO #OriginalRenewalDetails
FROM Shiva.dbo.ProductRemortgage PR WITH (NOLOCK)
LEFT JOIN Shiva.dbo.ClientLead AS CL WITH (NOLOCK)
ON CONVERT(VARCHAR(50), CL.OriginatorReferenceID) = CONVERT(VARCHAR(50), PR.ClientID)
WHERE CL.ClientID IS NULL
AND
(
(
PR.NewDealEndDate = DATEADD(dd, 90, DATEDIFF(dd, 00, GETDATE()))
AND Datepart(weekday, getdate()) <> 1 -- 1 is Sunday
)
OR
(
PR.NewDealEndDate BETWEEN DATEADD(dd, 88, DATEDIFF(dd, 00, GETDATE()))
AND DATEADD(dd, 90, DATEDIFF(dd, 00, GETDATE()))
AND Datepart(dayofweek, getdate()) = 1
)
)
declare #adjustment int--SELECT DATEPART(weekday, getdate())
set #adjustment =
CASE
WHEN DATEPART(weekday, getdate())
in (1,2,3,4,5) THEN 90
ELSE 88
END
WHERE
PR.NewDealEndDate BETWEEN DATEADD(dd, #adjustment...

How to convert a Cursor into SELECT queries?

I am using SSRS 2008 and i have a stored proc which currently uses cursors to delete and add data, but even after I convert this to select queries, I am getting error:
Msg 102, Level 15, State 1, Line 39
Incorrect syntax near ')'.
Here was the original Cursor which worked:
OPEN PARTS
FETCH PARTS INTO #PART_NUM,
#PART_DESC
SET #PARTS_FETCH = ##FETCH_STATUS
WHILE #PARTS_FETCH = 0 BEGIN
SET #THE_DATE = dateadd("yy", -1, dateadd("m", -1, getdate()))
SET #END_DATE = DATEADD(ms, -5, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))
-- Get PL for part number
Delete from #tbl_PL
Insert #tbl_PL
SELECT FRUD.tblXref.product_code FROM FRUD.tblfieldOrderablePart INNER JOIN
FRUD.MAX_APPROVED ON FRUD.tblfieldOrderablePart.fop_no = FRUD.MAX_APPROVED.fop_no AND
FRUD.tblfieldOrderablePart.fop_revision = FRUD.MAX_APPROVED.MaxOffop_revision INNER JOIN
FRUD.tblXref ON FRUD.MAX_APPROVED.fop_no = FRUD.tblXref.fop_no AND
FRUD.MAX_APPROVED.MaxOffop_revision = FRUD.tblXref.fop_revision
WHERE (dbo.FORMAT_PART(FRUD.tblfieldOrderablePart.fop_no) = dbo.FORMAT_PART(#PART_NUM))
-- End Get PL
WHILE #THE_DATE <= #END_DATE BEGIN
SET #THE_DATE = DATEADD(ms, -5, DATEADD(mm, DATEDIFF(m, 0, #THE_DATE) + 1, 0))
-- Get census using PL
SELECT #ALL_TOTAL = SUM(TheSum) FROM (SELECT CAST(RELIABILITY.Census.Census AS DECIMAL(9,2)) AS TheSum, (CONVERT(datetime, LEFT(CONVERT(char, Period), 4) + '-' + RIGHT(Period, 2) + '-1', 102)) as ThePeriod
FROM RELIABILITY.Census
WHERE RELIABILITY.Census.PL In (Select distinct * FROM #tbl_PL)
AND (CONVERT(datetime, LEFT(CONVERT(char, Period), 4) + '-' + RIGHT(Period, 2) + '-1', 102) >=
DATEADD(mm, DATEDIFF(mm, 0, #THE_DATE) - 5, 0)) AND (CONVERT(datetime, LEFT(CONVERT(char, Period), 4)
+ '-' + RIGHT(Period, 2) + '-1', 102) <= #THE_DATE) UNION ALL SELECT CAST(Census AS DECIMAL(9,2)) AS TheSum, Period FROM [MANUAL].SMARTSOLVE_CENSUS WHERE (Period >= DATEADD(mm, DATEDIFF(mm, 0, #THE_DATE) - 5, 0) AND Period <= #THE_DATE) AND (PL In (Select distinct * FROM #tbl_PL)))A
And here is my conversion to Select:
DECLARE #THE_DATE datetime,
#END_DATE datetime,
#THE_GOAL decimal(18,2),
#PART_NUM nvarchar(50),
#UNCHANGED_PART_NUM nvarchar(50),
#PART_DESC varchar(35),
#PARTS_FETCH int,
#NUM_FAILED int,
#AVG_CENSUS decimal(18,2),
#PL_VAR nvarchar(50),
#PL_FETCH int,
#PL_TOTAL decimal(9,2),
#ALL_TOTAL decimal(9,2)
--WHILE #PARTS_FETCH = 0 BEGIN
SET #THE_DATE = dateadd("yy", -1, dateadd("m", -1, getdate()))
SET #END_DATE = DATEADD(ms, -5, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))
--WHILE #THE_DATE <= #END_DATE BEGIN
SET #THE_DATE = DATEADD(ms, -5, DATEADD(mm, DATEDIFF(m, 0, #THE_DATE) + 1, 0))
-- Get census using PL
SELECT #ALL_TOTAL = SUM(TheSum) FROM
(SELECT CAST(RELIABILITY.Census.Census AS DECIMAL(9,2)) AS TheSum
from RELIABILITY.Census
WHERE RELIABILITY.Census.PL In (Select distinct * FROM #tbl_PL)
AND (CONVERT(datetime, LEFT(CONVERT(char, Period), 4) + '-' + RIGHT(Period, 2) + '-1', 102) >=
DATEADD(mm, DATEDIFF(mm, 0, #THE_DATE) - 5, 0)) AND (CONVERT(datetime, LEFT(CONVERT(char, Period), 4)+ '-' + RIGHT(Period, 2) + '-1', 102) <= #THE_DATE)
UNION ALL
SELECT CAST(Census AS DECIMAL(9,2)) AS TheSum, Period
FROM [MANUAL].SMARTSOLVE_CENSUS
WHERE (Period >= DATEADD(mm, DATEDIFF(mm, 0, #THE_DATE) - 5, 0) AND Period <= #THE_DATE) AND (PL In (Select distinct * FROM #tbl_PL))
))A
As Joel and Lamak pointed out you have an extra ) This is actually really easy to find if you use something like Instant SQL formatter This will give the error
)(11,3) expected token:Unknown
)(11,3) expected token:
It also formats the SQL as below which makes it a little easier to follow.
SELECT #ALL_TOTAL = SUM(thesum)
FROM (SELECT CAST(reliability.census.census AS DECIMAL(9, 2)) AS thesum
FROM reliability.census
WHERE reliability.census.pl IN (SELECT DISTINCT *
FROM #tbl_pl)
AND ( CONVERT(DATETIME, LEFT(CONVERT(CHAR, period), 4) + '-' +
RIGHT(
period, 2)
+
'-1'
, 102) >= Dateadd(mm, Datediff(mm, 0, #THE_DATE) - 5, 0) )
AND ( CONVERT(DATETIME, LEFT(CONVERT(CHAR, period), 4)+ '-' +
RIGHT(
period, 2) +
'-1',
102) <= #THE_DATE )
UNION ALL
SELECT CAST(census AS DECIMAL(9, 2)) AS thesum,
period
FROM [MANUAL].smartsolve_census
WHERE ( period >= Dateadd(mm, Datediff(mm, 0, #THE_DATE) - 5, 0)
AND period <= #THE_DATE )
AND ( pl IN (SELECT DISTINCT *
FROM #tbl_pl) ))a
Sounds like you have mis-matched parentheses, double check and make sure they all line up correctly. You have one more ")" at the end of that last select statement than you have ever being opened. That's a lot of nesting! Make sure everything matches up how you intended, or you may get unexpected results if your UNION gets applied at the wrong level or something.
If I'm reading your query correctly, you have two errors. The first is an extra ")" on the last line, it should be:
WHERE (Period >= DATEADD(mm, DATEDIFF(mm, 0, #THE_DATE) - 5, 0) AND Period <= #THE_DATE) AND (PL In (Select distinct * FROM #tbl_PL))
) A
And, I think you also have more columns on your query after the UNION ALL, you are selecting CAST(Census AS DECIMAL(9,2)) AS TheSum, Period and on the first one you are selecting only one column: CAST(RELIABILITY.Census.Census AS DECIMAL(9,2)) AS TheSum