Kindly see my Stored Proc below. I'm trying to pass through a value of 1 or 0 from a parameter in a CASE statement.
I get the error which I can tell are in the SELECT statement calling the parameter #payment_status in the CASE statment:
Msg 102, Level 15, State 1, Line 17 Incorrect syntax near '='.
Msg 102, Level 15, State 1, Line 21 Incorrect syntax near '='.
Here's the script:
ALTER PROC ash_ap_cash_req_sp (#End_Date NVARCHAR(12),
#Payment_Hold NVARCHAR(32))
AS
SET NOCOUNT ON
DECLARE #debug INT,
#julian_end_date VARCHAR(7),
#ap_cash_req NVARCHAR(4000),
#payment_status VARCHAR(400)
SET #End_Date = RIGHT('00' + CONVERT(VARCHAR(2), datepart(mm, #End_Date)), 2) + '/' + RIGHT('00' + CONVERT(VARCHAR(2), datepart(dd, #End_Date)), 2) + '/' + RIGHT('0000' + CONVERT(VARCHAR(4), datepart(yyyy, #End_Date)), 4)
SET #julian_end_date = (SELECT datediff(dd, '1/1/1753', #End_Date) + 639906)
IF #Payment_Hold = 'All'
BEGIN
SET #payment_status = '
SELECT payment_hold_flag
FROM dbase.dbo.apvchr
WHERE payment_hold_flag in (0,1)'
END
ELSE IF #Payment_Hold = 'Yes'
BEGIN
SET #payment_status = '
SELECT payment_hold_flag
FROM dbase.dbo.apvchr
WHERE payment_hold_flag = 1'
END
ELSE IF #Payment_Hold = 'No'
BEGIN
SET #payment_status = '
SELECT payment_hold_flag
FROM dbase.dbo.apvchr
WHERE payment_hold_flag = 0'
END
SET #debug = 0
SET #ap_cash_req = '
IF OBJECT_ID(''temp.dbo.##ash_ap_cash_req_sp'') is NOT NULL
DROP TABLE ##ash_ap_cash_req_sp;
CREATE TABLE ##ash_ap_cash_req_sp
(vendor varchar(12)
, pay_to varchar(12)
, vendor_name varchar(32)
, voucher_no varchar(12)
, invoice_no varchar(32)
, date_doc varchar(12)
--, date_doc_jd varchar(12)
, date_due varchar(12)
--, date_due_jd varchar(12)
, date_applied varchar(12)
--, date_applied_jd varchar(12)
, paid_status varchar(8)
--, payment_status varchar(12)
, payment_hold_status varchar(8)
, amount_open decimal(20,2)
, days_diff float
, days_0_to_30 decimal(20,2)
, days_31_to_60 decimal(20,2)
, days_61_to_90 decimal(20,2)
, days_91_to_120 decimal(20,2)
, days_121_to_150 decimal(20,2)
, total_over_90 decimal(20,2)
, total_over_150 decimal(20,2)
, payment_code varchar(8)
)'
IF #debug = 1
BEGIN
PRINT #ap_cash_req
PRINT ''
END
ELSE
BEGIN
EXEC sp_executesql #ap_cash_req
END
SET #ap_cash_req = '
SELECT
m.vendor
, m.pay_to
, m.address_name as vendor_name
, h.trx_ctrl_num as voucher_no
, h.doc_ctrl_num as invoice_no
, CONVERT(varchar(12),dateadd(dd,(h.date_doc- 639906),''1/1/1753''),101) as date_doc
--, h.date_doc as date_doc_jd
, CONVERT(varchar(12),dateadd(dd,(h.date_due- 639906),''1/1/1753''),101) as date_due
--, h.date_due as date_due_jd
, CONVERT(varchar(12),dateadd(dd,(h.date_applied- 639906),''1/1/1753''),101) as date_applied
--, h.date_applied as date_applied_jd
, paid_status = CASE WHEN h.paid_flag = 1
THEN ''Paid''
ELSE ''Not Paid'' END
, h.payment_hold_flag = CASE
WHEN ' + #payment_status + ' = 1 THEN ''On Hold''
ELSE ''Not On Hold''
END as payment_hold_status
, amount_open = (amt_net-amt_paid_to_date)
, h.payment_code
, days_dif = (' + #julian_end_date + ' - h.date_applied)
, days_0_to_30 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-30
THEN h.amt_net --(h.amt_net-h.amt_paid_to_date)
ELSE 0 END
, days_31_to_60 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-60
AND h.date_applied <= ' + #julian_end_date + '-31
THEN h.amt_net
ELSE 0 END
, days_61_to_90 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-90
AND h.date_applied <= ' + #julian_end_date + '-61
THEN h.amt_net
ELSE 0 END
, days_91_to_120 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-120
AND h.date_applied <= ' + #julian_end_date + '-91
THEN h.amt_net
ELSE 0 END
, days_121_to_150 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-150
AND h.date_applied <= ' + #julian_end_date + '-121
THEN h.amt_net
ELSE 0 END
, total_over_90 = CASE WHEN h.date_applied <= ' + #julian_end_date + '-91
THEN h.amt_net
ELSE 0 END
, total_over_150 = CASE WHEN h.date_applied <= ' + #julian_end_date + '-151
THEN h.amt_net
ELSE 0 END
FROM dbase.dbo.apvchr h
JOIN dbase.dbo.apvdet d
ON h.trx_ctrl_num = d.trx_ctrl_num
JOIN dbase.dbo.master m
ON h.vendor = m.vendor
AND h.pay_to = m.pay_to
GROUP BY m.vendor, m.pay_to, m.address_name
, h.trx_ctrl_num, h.doc_ctrl_num, h.date_doc, h.date_due, h.date_applied, h.paid_flag, h.payment_hold_flag
, h.amt_net, h.amt_paid_to_date, h.payment_code, h.payment_hold_flag
--ORDER BY NEWID()
'
IF #debug = 1
BEGIN
PRINT #ap_cash_req
PRINT ''
END
ELSE
BEGIN
EXEC sp_executesql #ap_cash_req
END
SET #ap_cash_req = '
SELECT * FROM ##ash_ap_cash_req_sp
';
SET #ap_cash_req = '
DROP TABLE ##ash_ap_cash_req_sp
';
IF #debug = 1
BEGIN
PRINT #ap_cash_req
PRINT ''
END
ELSE
BEGIN
EXEC sp_executesql #ap_cash_req
END
EXEC dbase.dbo.ash_ap_cash_req_sp;1 '03/11/2013','Yes'
Because #payment_status is a 'SELECT...', you'll need to wrap it with braces
h.payment_hold_flag = CASE
WHEN ('+#payment_status+') = 1 THEN ''On Hold''
ELSE ''Not On Hold''
END as payment_hold_status
but, that aside, I would question the syntax :
, amount_open = (amt_net-amt_paid_to_date)
- do you mean
, (amt_net-amt_paid_to_date) as amount_open?
Related
As we can have a command like this in C# or Java
return 1 < 2;
Is it possible to do something like that in SQL?
SELECT 1 < 2
or in my case:
Select
Case when sign = '<' then col1 < 10 else col1 > 10 end
from ...
Result: 0
When I use SELECT 1 < 2 I get an error:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '<'.
So it seems that there is a problem with this statement. I'm using TSQL.
I don't know what DBMS you are using, I am using T-SQL in this example. This should work:
declare #col1 int
declare #sign varchar(1)
set #col1 = 10
set #sign = '<'
Select
case when (#sign = '<') and (#col1 < 10) then 1
when (#sign = '>') and (#col1 > 10) then 1
else 0
end
I think you mean this:
DECLARE #Col1 INT = 10; --Set your value
SELECT Result = CASE WHEN #Col1 > 10 THEN CAST(#Col1 AS VARCHAR(10) ) + ' > 10'
WHEN #Col1 < 10 THEN CAST(#Col1 AS VARCHAR(10) ) + ' < 10'
ELSE CAST(#Col1 AS VARCHAR(10) ) + ' = 10'
END
OR
DECLARE #Col1 INT = 10;
DECLARE #VarForCompare INT = 55;
SELECT Result = CASE WHEN #Col1 > #VarForCompare THEN CAST(#Col1 AS VARCHAR(10) ) + ' > ' + CAST(#VarForCompare AS VARCHAR(10) )
WHEN #Col1 < #VarForCompare THEN CAST(#Col1 AS VARCHAR(10) ) + ' < ' + + CAST(#VarForCompare AS VARCHAR(10) )
ELSE CAST(#Col1 AS VARCHAR(10) ) + ' = ' + + CAST(#VarForCompare AS VARCHAR(10) )
END
OR using IF:
IF #Col1 > #VarForCompare
SELECT CAST(#Col1 AS VARCHAR(10) ) + ' > ' + CAST(#VarForCompare AS VARCHAR(10) ) Result
ELSE
IF #Col1 < #VarForCompare
SELECT CAST(#Col1 AS VARCHAR(10) ) + ' < ' + CAST(#VarForCompare AS VARCHAR(10) ) Result
ELSE
SELECT CAST(#Col1 AS VARCHAR(10) ) + ' = ' + CAST(#VarForCompare AS VARCHAR(10) ) Result
I don't see why you need Sign variable.
select case when 1 <2 then 'true' else 'false' end
You could also use the inline if statement instead of CASE:
SELECT IIF(1 < 2,'true','false')
I want to have the procedure which includes dynamic query and giving perfect result. But I want to use the procedure in another procedure.
When I write the query like
select procedurename from table name t1
it returns
procedure is not a recognized built-in function name.
Simply call testa from testb like:
EXEC testa #newId, #prod, #desc;
Make sure to get #id using:
SELECT #newId = ##SCOPE_IDENTITY
You should cteate a temporary table out of your procedure and insert the result of your first proc using INSERT..EXEC:
create #t (...);
insert #t(...) exec sp1;
At this point your second proc can use #t to select from it
Another solution can be turning your proc into multi-statement function but it's not the case since you use a dynamic code
i have a table named savedsearch which has few columns named username mobile lastloginbefore etc
Then i use this procedure for dynamic query
ALTER PROCEDURE [dbo].[usp_GetCouponStatusProcedure1] --26072,54
#UserID INT,
#SavedSearch VARCHAR(550)
AS
BEGIN
DECLARE #Email1 VARCHAR(50),
#Mobile1 VARCHAR(50),
#UserFilter1 VARCHAR(50),
#UserName1 VARCHAR(50),
#UserType1 VARCHAR(50),
#LastLoginBefore1 VARCHAR(50),
#LastLogin1 VARCHAR(50),
#LastPurchase1 VARCHAR(50)
SELECT #UserName1 = ss.UserName,
#Email1 = ss.EmailID,
#Mobile1 = ss.Mobile,
#UserFilter1 = ss.UserFilter,
#UserType1 = ss.UserType,
#LastLoginBefore1 = ss.LastLoginBefore,
#LastPurchase1 = ss.LastPurchase,
#LastLogin1 = ss.LastLogin
FROM SavedSearch AS ss
WHERE ss.ID = #SavedSearch
DECLARE #String NVARCHAR(1000) =
'SELECT SearchName into #Temp
FROM SavedSearch AS ss '
DECLARE #LastLogin VARCHAR(500),
#Email VARCHAR(500),
#Mobile VARCHAR(500),
#UserFilter VARCHAR(500),
#UserName VARCHAR(500),
#UserType VARCHAR(500),
#LastLoginBefore VARCHAR(500),
#LastPurchase VARCHAR(500),
#WhereClause VARCHAR(500),
#WhereClause1 VARCHAR(500),
#WhereClause2 VARCHAR(500),
#WhereClause3 VARCHAR(500),
#WhereClause4 VARCHAR(500),
#WhereClause5 VARCHAR(500),
#WhereClause6 VARCHAR(500),
#WhereClause7 VARCHAR(500),
#WhereClause8 VARCHAR(500)
SET #WhereClause = ' WHERE ss.ID = #SavedSearch1 AND ('
DECLARE #i INT
IF #LastLogin1 <> 0
BEGIN
SET #LastLogin =
' CROSS APPLY funcToGetNewUserLastLogin(ss.LastLogin) AS ftll '
SET #WhereClause1 = ' ftll.[User_ID] = #UserID1 '
END
IF #Email1 <> ''
BEGIN
SET #Email =
' CROSS APPLY funcToGetUserForGivenEmail(ss.EmailID) AS ftEm '
SET #WhereClause2 = ' ftEm.[User_ID] = #UserID1 '
END
IF #Mobile1 <> 0
BEGIN
SET #Mobile =
' CROSS APPLY funcToGetUserForGivenMobile(ss.Mobile) AS ftmo '
SET #WhereClause3 = ' ftmo.[User_ID] = #UserID1 '
END
IF #UserFilter1 <> ''
BEGIN
SET #UserFilter =
' CROSS APPLY funcToGetUserForGivenUserFilter(ss.UserFilter) AS ftUf '
SET #WhereClause4 = ' ftUf.[User_ID] = #UserID1 '
END
IF #UserName1 <> ''
BEGIN
SET #UserName =
' CROSS APPLY funcToGetUserForGivenUserName(ss.UserName) AS ftun '
SET #WhereClause5 = ' ftun.[User_ID] = #UserID1 '
END
IF #UserType1 <> ''
BEGIN
SET #UserType =
' CROSS APPLY funcToGetUserForGivenUserType(ss.UserType) AS ftut '
SET #WhereClause6 = ' ftut.[User_ID] = #UserID1 '
END
IF #LastLoginBefore1 <> 0
BEGIN
SET #LastLoginBefore =
' CROSS APPLY funcToGetUserLastLoginBefore(ss.LastLoginBefore) AS ftlb '
SET #WhereClause7 = ' ftlb.[User_ID] = #UserID1 '
END
IF #LastPurchase1 <> 0
BEGIN
SET #LastPurchase =
' CROSS APPLY funcToGetUserLastPurchased(ss.LastPurchase) AS ftpur '
SET #WhereClause8 = ' ftpur.[User_ID] = #UserID1 '
END
SET #String = #String + ISNULL(#Email, '') + ISNULL(#UserName, '') + ISNULL(#UserType, '')
+ ISNULL(#UserFilter, '') + ISNULL(#LastLogin, '')
+ ISNULL(#LastLoginBefore, '') + ISNULL(#LastPurchase, '') + ISNULL(#Mobile, '')
+ ISNULL(#WhereClause, '') + CASE
WHEN #WhereClause1 <> '' THEN CASE
WHEN
#WhereClause2
<
>
''
OR
#WhereClause3
<
>
''
OR
#WhereClause8
<
>
''
OR
#WhereClause7
<
>
''
OR
#WhereClause6
<
>
''
OR
#WhereClause5
<
>
''
OR
#WhereClause4
<
>
'' THEN
ISNULL(#WhereClause1, '')
+
' OR '
ELSE
ISNULL(#WhereClause1, '')
END
ELSE ''
END + CASE
WHEN #WhereClause2 <> '' THEN CASE
WHEN
#WhereClause3
<
>
''
OR
#WhereClause8
<
>
''
OR
#WhereClause7
<
>
''
OR
#WhereClause6
<
>
''
OR
#WhereClause5
<
>
''
OR
#WhereClause4
<
>
'' THEN
ISNULL(#WhereClause2, '')
+
' OR '
ELSE
ISNULL(#WhereClause2, '')
END
ELSE ''
END + CASE
WHEN #WhereClause3 <> '' THEN CASE
WHEN
#WhereClause8
<
>
''
OR
#WhereClause7
<
>
''
OR
#WhereClause6
<
>
''
OR
#WhereClause5
<
>
''
OR
#WhereClause4
<
>
'' THEN
ISNULL(#WhereClause3, '')
+
' OR '
ELSE
ISNULL(#WhereClause3, '')
END
ELSE ''
END + CASE
WHEN #WhereClause4 <
> '' THEN CASE
WHEN
#WhereClause8
<
>
''
OR
#WhereClause7
<
>
''
OR
#WhereClause6
<
>
''
OR
#WhereClause5
<
>
'' THEN
ISNULL(#WhereClause4, '')
+
' OR '
ELSE
ISNULL(#WhereClause4, '')
END
ELSE ''
END + CASE
WHEN #WhereClause5
<> '' THEN CASE
WHEN
#WhereClause8
<
>
''
OR
#WhereClause7
<
>
''
OR
#WhereClause6
<
>
'' THEN
ISNULL(#WhereClause5, '')
+
' OR '
ELSE
ISNULL(#WhereClause5, '')
END
ELSE ''
END + CASE
WHEN #WhereClause6
<>
'' THEN CASE
WHEN
#WhereClause8
<
>
''
OR
#WhereClause7
<
>
'' THEN
ISNULL(#WhereClause6, '')
+
' OR '
ELSE
ISNULL(#WhereClause6, '')
END
ELSE ''
END + CASE
WHEN
#WhereClause7
<
>
'' THEN CASE
WHEN
#WhereClause8
<
>
'' THEN
ISNULL(#WhereClause7, '')
+
' OR '
ELSE
ISNULL(#WhereClause7, '')
END
ELSE
''
END + CASE
WHEN
#WhereClause6
<
>
'' THEN
ISNULL(#WhereClause6, '')
ELSE
''
END
+ ' )'
DECLARE #ParmDefinition NVARCHAR(500) =
N'#UserID1 INT, #SavedSearch1 varchar(500),#ii int OUTPUT';
DECLARE #UserID1 INT,
#SavedSearch1 VARCHAR(500)
EXECUTE sp_executesql #String,
#ParmDefinition,
#UserID1 = #UserID,
#SavedSearch1 = #SavedSearch,
#ii = #i OUTPUT
DECLARE #rowcount INT
SET #rowcount = ##rowcount
SELECT --#SavedSearch AS savedsearchid,
#rowcount AS ReturnedValue
--PRINT #String
--SELECT #i
END
I have the following code for a SQL Query I'm working on..
DECLARE #Date datetime
SET #Date = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
DECLARE #jobHistory TABLE
(
job_id UNIQUEIDENTIFIER
, success INT
, cancel INT
, fail INT
, retry INT
, last_execution_id INT
, last_duration CHAR(8)
, last_execution_start DATETIME
);
WITH lastExecution
AS
(
SELECT job_id
, MAX(instance_id) AS last_instance_id
FROM msdb.dbo.sysjobhistory
WHERE step_id = 0
GROUP BY job_id
)
INSERT INTO #jobHistory
SELECT sjh.job_id
, SUM(CASE WHEN sjh.run_status = 1 AND step_id = 0 THEN 1 ELSE 0 END) AS success
, SUM(CASE WHEN sjh.run_status = 3 AND step_id = 0 THEN 1 ELSE 0 END) AS cancel
, SUM(CASE WHEN sjh.run_status = 0 AND step_id = 0 THEN 1 ELSE 0 END) AS fail
, SUM(CASE WHEN sjh.run_status = 2 THEN 1 ELSE 0 END) AS retry
, MAX(CASE WHEN sjh.step_id = 0 THEN instance_id ELSE NULL END) last_execution_id
, SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),2,2) + ':'
+ SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),4,2) + ':'
+ SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),6,2)
AS last_duration
, MAX(CASE WHEN le.last_instance_id IS NOT NULL THEN
CONVERT(datetime, RTRIM(run_date))
+ ((run_time / 10000 * 3600)
+ ((run_time % 10000) / 100 * 60)
+ (run_time % 10000) % 100) / (86399.9964)
ELSE '1900-01-01' END) AS last_execution_start
FROM msdb.dbo.sysjobhistory AS sjh
LEFT JOIN lastExecution AS le
ON sjh.job_id = le.job_id
AND sjh.instance_id = le.last_instance_id
GROUP BY sjh.job_id;
DECLARE #weekDay TABLE (
mask INT
, maskValue VARCHAR(32)
);
INSERT INTO #weekDay
SELECT 1, 'Sunday' UNION ALL
SELECT 2, 'Monday' UNION ALL
SELECT 4, 'Tuesday' UNION ALL
SELECT 8, 'Wednesday' UNION ALL
SELECT 16, 'Thursday' UNION ALL
SELECT 32, 'Friday' UNION ALL
SELECT 64, 'Saturday';
WITH myCTE
AS(
SELECT sched.name AS 'scheduleName'
, sched.schedule_id
, jobsched.job_id
, CASE
WHEN sched.freq_type = 1
THEN 'Once'
WHEN sched.freq_type = 4
AND sched.freq_interval = 1
THEN 'Daily'
WHEN sched.freq_type = 4
THEN 'Every ' + CAST(sched.freq_interval AS VARCHAR(5)) + ' days'
WHEN sched.freq_type = 8 THEN
REPLACE( REPLACE( REPLACE((
SELECT maskValue
FROM #weekDay AS x
WHERE sched.freq_interval & x.mask <> 0
ORDER BY mask FOR XML RAW)
, '"/><row maskValue="', ', '), '<row maskValue="', ''), '"/>', '')
+ CASE
WHEN sched.freq_recurrence_factor <> 0
AND sched.freq_recurrence_factor = 1
THEN '; weekly'
WHEN sched.freq_recurrence_factor <> 0
THEN '; every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' weeks' END
WHEN sched.freq_type = 16 THEN 'On day '
+ CAST(sched.freq_interval AS VARCHAR(10)) + ' of every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' months'
WHEN sched.freq_type = 32 THEN
CASE
WHEN sched.freq_relative_interval = 1 THEN 'First'
WHEN sched.freq_relative_interval = 2 THEN 'Second'
WHEN sched.freq_relative_interval = 4 THEN 'Third'
WHEN sched.freq_relative_interval = 8 THEN 'Fourth'
WHEN sched.freq_relative_interval = 16 THEN 'Last'
END +
CASE
WHEN sched.freq_interval = 1 THEN ' Sunday'
WHEN sched.freq_interval = 2 THEN ' Monday'
WHEN sched.freq_interval = 3 THEN ' Tuesday'
WHEN sched.freq_interval = 4 THEN ' Wednesday'
WHEN sched.freq_interval = 5 THEN ' Thursday'
WHEN sched.freq_interval = 6 THEN ' Friday'
WHEN sched.freq_interval = 7 THEN ' Saturday'
WHEN sched.freq_interval = 8 THEN ' Day'
WHEN sched.freq_interval = 9 THEN ' Weekday'
WHEN sched.freq_interval = 10 THEN ' Weekend'
END
+ CASE
WHEN sched.freq_recurrence_factor <> 0
AND sched.freq_recurrence_factor = 1
THEN '; monthly'
WHEN sched.freq_recurrence_factor <> 0
THEN '; every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' months'
END
WHEN sched.freq_type = 64 THEN 'StartUp'
WHEN sched.freq_type = 128 THEN 'Idle'
END AS 'frequency'
, ISNULL('Every ' + CAST(sched.freq_subday_interval AS VARCHAR(10)) +
CASE
WHEN sched.freq_subday_type = 2 THEN ' seconds'
WHEN sched.freq_subday_type = 4 THEN ' minutes'
WHEN sched.freq_subday_type = 8 THEN ' hours'
END, 'Once') AS 'subFrequency'
, REPLICATE('0', 6 - LEN(sched.active_start_time))
+ CAST(sched.active_start_time AS VARCHAR(6)) AS 'startTime'
, REPLICATE('0', 6 - LEN(sched.active_end_time))
+ CAST(sched.active_end_time AS VARCHAR(6)) AS 'endTime'
, REPLICATE('0', 6 - LEN(jobsched.next_run_time))
+ CAST(jobsched.next_run_time AS VARCHAR(6)) AS 'nextRunTime'
, CAST(jobsched.next_run_date AS CHAR(8)) AS 'nextRunDate'
FROM msdb.dbo.sysschedules AS sched
JOIN msdb.dbo.sysjobschedules AS jobsched
ON sched.schedule_id = jobsched.schedule_id
WHERE sched.enabled = 1
)
SELECT job.name AS [Job Name]
, CASE WHEN job.enabled = 1 THEN 'Enabled' ELSE 'Disabled' END AS [Job Status]
, COALESCE(sched.subFrequency, '') AS [Frequency]
, COALESCE(jh.last_duration, '') AS [Last Run Duration]
, COALESCE(jh.last_execution_start, '') AS [Last Run Time/Date]
FROM msdb.dbo.sysjobs AS job
LEFT JOIN myCTE AS sched
ON job.job_id = sched.job_id
LEFT JOIN #jobHistory AS jh
ON job.job_id = jh.job_id
WHERE jh.last_execution_start >= DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
AND job.name like '%MAINTENANCE - BACKUP%'
ORDER BY nextRunDate;
but although the results show the expected 'Failed' jobs, the 'Disabled' jobs are missing. I have also had help with this, as I have no SQL experience.
This Query has been created to check the Job History of roughtly 5/10 Backup Jobs within a 24 hour period, noting all the Failures (even if the last Run Succeeded). The seconds on the [Last Run Time/Date] also seem to be off, showing as soemthign like '50:00.0'
I also need a new column for the [Last Run Outcome] - to show if the Job 'Failed/Succeeded' as a Status.
Please let me know if you require any further information or a PasteBin of my code.
I am trying to display data with 11 months from 11 tables. Each table containing a different months data. The table name contains the date of each table. At the moment my code works in a way that a person has to input a date such as 201404 then it will display all months from 201404 right up to 201503. I need to put a check in place so that if the person types in 201507 it only throws out 201507 up to 201510 as the remaining months do not exists as yet.
This is my code:
alter PROCEDURE stp3
#FirstTableMonth int =0,
#EndMonth datetime
AS
DECLARE
#LinkedServerName sysname = 'SERVER1',
#left int = 0,
#right int= 0,
#STRING VARCHAR(6),
#monthex int = 12,
#yearex int,
#yearstring int,
#DynamicSQL nvarchar(max) = '',
#DynamicSQL2 nvarchar(max) = '',
#OpenQuerySql nvarchar(max),
#Table_Name sysname,
#Table_Name2 sysname,
#TableMonth int,
#TableMonth2 int ,
#CurrentMonth int = 0,
#NextYearMonth int = 1,
#part2 nvarchar(max) = '',
#TwelfthMonth int = 0;
SET #FirstTableMonth= CAST(#FirstTableMonth AS VARCHAR(6))
set #left = cast(left(#FirstTableMonth,4) +1 as varchar(max))
set #right = right(#FirstTableMonth,2) - 1
set #monthex = 11
set #yearex = cast(left(#FirstTableMonth,4) as varchar(max))
set #yearstring = case when right(#FirstTableMonth,2) = '01' then left(#FirstTableMonth,4) + RIGHT( #monthex + LTRIM( RTRIM( right(#FirstTableMonth,2) ) ), 6 ) else #left end
SET #STRING =
case when right(#FirstTableMonth,2) = '01' then #yearstring
when #right < 10 then CAST(#left AS VARCHAR(4)) + RIGHT( '0' + LTRIM( RTRIM( #right ) ), 6 )
else CAST(#left AS VARCHAR(4)) + RIGHT( LTRIM( RTRIM( #right ) ), 6 ) end
WHILE #CurrentMonth < 11 AND #EndMonth < getdate()
BEGIN
SELECT #TableMonth = CASE WHEN (#FirstTableMonth + #CurrentMonth) % 100 < 13 THEN
#FirstTableMonth + #CurrentMonth
ELSE
#FirstTableMonth + 100 - (#FirstTableMonth % 100) + #NextYearMonth
END,
#NextYearMonth = CASE WHEN (#FirstTableMonth + #CurrentMonth) % 100 < 13 THEN
#NextYearMonth
ELSE
#NextYearMonth + 1
END,
#Table_Name = 'XX_'+CAST(#TableMonth as varchar)+'_T' ,
#TableMonth2 = #TableMonth,
#Table_Name2 = 'XX_'+CAST(#TableMonth2 as varchar)+'_T' ,
#DynamicSQL = #DynamicSQL +
'SELECT
*
FROM '+ #Table_Name + '
'+ CASE WHEN #CurrentMonth < 10 THEN ' UNION ALL ' ELSE '' END ,
#DynamicSQL2 = #DynamicSQL2 +
'SELECT
*
FROM '+ #Table_Name2 + '
'
SET #CurrentMonth = #CurrentMonth + 1
IF OBJECT_ID('tempdb..#TEMP') IS NOT NULL BEGIN DROP TABLE #TEMP END
IF OBJECT_ID('tempdb..#Unioned') IS NOT NULL BEGIN DROP TABLE #Unioned END
--last months snapshot
SELECT
*
INTO #UNIONED
FROM OPENQUERY(SERVER1,' SELECT
*
FROM yy_T
'
)
union all
SELECT
*
FROM OPENQUERY(SERVER1,' SELECT
*
FROM yk
'
)
DECLARE #dateAsNumber VARCHAR(8);
SET #dateAsNumber = CONVERT(CHAR(6),GETDATE(), 112);
DECLARE #DateConvertedFromNumber DATETIME;
SELECT #DateConvertedFromNumber = CONVERT (DATETIME, CONVERT(CHAR(8), #dateAsNumber + '01'))
select
*
LEFT(CONVERT(VARCHAR, DATEADD(MONTH, -1,#DateConvertedFromNumber), 112),6) AS 'Period'
INTO #temp
from #Unioned
drop table OpenQTable
--if equal to month + 99 = previous month then union 11 tables with last months snapshot
--else
--union 11 tables with 12th table
SET #OpenQuerySql = 'IF (' + cast(#FirstTableMonth as varchar) + '+99) = CONVERT(nvarchar(6), dateadd(month,-1,GETDATE()), 112)
BEGIN
SELECT *
FROM OPENQUERY(['+ #LinkedServerName +'], '''+ #DynamicSQL + ''' )
UNION ALL
SELECT *
FROM #temp
END
else
begin
SELECT *
FROM OPENQUERY(['+ #LinkedServerName +'], '''+ #DynamicSQL + ''' )
UNION ALL
SELECT *
FROM OPENQUERY(['+ #LinkedServerName +'], '''+ #DynamicSQL2 + ''' )
end
'
END
insert into OpenQTable
EXECUTE sp_executesql #OpenQuerySql
go
}
I have a stored procedure as following, I need to pass paramters to the dynamic pivot. My query runs, I just need to do some filtering based on the passed parameters
-- AND (#SelectedSystemIDs IS NULL OR System.ID IN(select * from dbo.SplitInts_RBAR_1(#SelectedSystemIDs, ',')))
--AND ((#PlatformID IS NULL) OR (System.PlatformID = #PlatformID) OR (#PlatformID = 12 AND System.PlatformID <= 2))
-- AND (ServiceEntry.ServiceDateTime between #StartDate and #EndDate)
so I want to add the above criteria, how could achieve that?
ALTER PROCEDURE [dbo].[spExportStuff]
(#StartDate datetime,
#EndDate datetime,
#SelectedSystemIDs nvarchar (2000) = NULL,
#SelectedTsbIDs nvarchar (2000) = NULL,
#UserRoleID int
)
AS
DECLARE #InstrumentType int = NULL
DECLARE #PlatformID int = null
IF (#SelectedSystemIDs = '')
begin
SET #SelectedSystemIDs = NULL
END
IF (#SelectedTsbIDs = '')
begin
SET #SelectedTsbIDs = NULL
END
IF(#UserRoleID = 1)
BEGIN
SET #PlatformID = 1
END
IF(#UserRoleID = 2)
BEGIN
SET #PlatformID = 2
END
IF (#UserRoleID = 3)
BEGIN
SET #PlatformID = 12
END
IF(#UserRoleID = 4)
BEGIN
SET #PlatformID = 3
END
IF(#UserRoleID = 5)
BEGIN
SET #PlatformID = 4
END
IF(#UserRoleID = 6)
BEGIN
SET #PlatformID = NULL
END
DECLARE #PivotColumnHeaders NVARCHAR(MAX)
SELECT #PivotColumnHeaders =
COALESCE(
#PivotColumnHeaders + ',[' + cast(SystemFullName as Nvarchar) + ']',
'[' + cast(SystemFullName as varchar)+ ']'
)
FROM System
DECLARE #PivotTableSQL NVARCHAR(MAX)
SET #PivotTableSQL = N'
SELECT *
FROM (
SELECT
TSBNumber [TSBNumber],
SystemFullName,
ClosedDate
FROM ServiceEntry
INNER JOIN System
ON ServiceEntry.SystemID = System.ID
Group By TSBNumber, SystemFullName, ClosedDate
) AS PivotData
PIVOT (
max(ClosedDate)
FOR SystemFullName IN (
' + #PivotColumnHeaders + '
)
) AS PivotTable
'
EXECUTE(#PivotTableSQL)
you can construct the required criteria as another input to the stored procedure and append it to the dynamic query
ALTER PROCEDURE [dbo].[spExportStuff]
(#StartDate datetime,
#EndDate datetime,
#SelectedSystemIDs nvarchar (2000) = NULL,
#SelectedTsbIDs nvarchar (2000) = NULL,
#UserRoleID int,
#WhereClause varchar(max) -> this is the new parameter.
)
DECLARE #PivotTableSQL NVARCHAR(MAX)
SET #PivotTableSQL = N'
SELECT *
FROM (
SELECT
TSBNumber [TSBNumber],
SystemFullName,
ClosedDate
FROM ServiceEntry
INNER JOIN System
ON ServiceEntry.SystemID = System.ID
Group By TSBNumber, SystemFullName, ClosedDate
) AS PivotData
PIVOT (
max(ClosedDate)
FOR SystemFullName IN (
' + #PivotColumnHeaders + '
)
) AS PivotTable
' + #WhereClause -> you can append the where clause here.
EXECUTE(#PivotTableSQL)