order by not working in stored procedure mysql - mysql

select
tr.TransactionId as TxnIdentifier,
m.MerchantName as MerchantName,
case
when tr.ChannelType=2 then 'ACH'
when tr.ChannelType=3 then 'CC'
when tr.ChannelType=4 then 'Debit'
else null
end as ChannelType,
tr.CaptureAmount as CaptureAmount,
case when tr.OperationType=0 then 'Sale'
when tr.OperationType=1 then 'Verify only'
when tr.OperationType=2 then 'ForceSale'
when tr.OperationType=3 then 'Adjust'
when tr.OperationType=4 then 'Activate'
when tr.OperationType=5 then 'Deactivate'
when tr.OperationType=6 then 'Reload'
when tr.OperationType=7 then 'Refund'
when tr.OperationType=8 then 'Inquire'
else null end as TxnType,
case when tr.TransactionStatus=0 then 'Created'
when tr.TransactionStatus=1 then 'Pending'
when tr.TransactionStatus=2 then 'Authorized'
when tr.TransactionStatus=3 then 'Posted'
when tr.TransactionStatus=4 then 'Accepted'
when tr.TransactionStatus=5 then 'Failed'
when tr.TransactionStatus=6 then 'Returned'
when tr.TransactionStatus=7 then 'Chargeback'
when tr.TransactionStatus=8 then 'Void'
when tr.TransactionStatus=9 then 'Refunded'
when tr.TransactionStatus=10 then 'Approved'
when tr.TransactionStatus=11 then 'Void attempted'
when tr.TransactionStatus=12 then 'Refund attempted'
when tr.TransactionStatus=13 then 'Hold'
when tr.TransactionStatus=14 then 'Denied'
when tr.TransactionStatus=15 then 'Settlement hold'
when tr.TransactionStatus=16 then 'Success'
when tr.TransactionStatus=17 then 'Retried'
when tr.TransactionStatus=100 then 'Unknown'
else null end as TxnStatus,
tr.PreAuthCode as AuthCode,
DATE_FORMAT(tr.TransactionDate, '%m-%d-%Y %H:%i:%s') as TransactionDate,
case when tr.OperationType='7' then tr.Amount
else null end as RefundAmount,
case when tr.OperationType='7'
then DATE_FORMAT(tr.TransactionDate, '%m-%d-%Y %H:%i:%s')
else null end as RefundedOn,
tr.TraceNumber as TraceNumber
from TransactionEntity tr
inner join `enter code here`DOMAIN.Merchant m on m.Id=tr.MerchantId where 1=1
and (tr.MerchantId = merchantId or merchantId=0)
and (tr.ChannelType = channelType or channelType=0)
And (tr.TransactionDate >= startDate or startDate is null)
And (tr.TransactionDate <= endDate or endDate is null)
ORDER BY
CASE WHEN sortField = 'TransactionDate' AND sortDirection='ASC' THEN TransactionDate END ASC,
CASE WHEN sortField = 'TransactionDate' AND sortDirection='DESC' THEN TransactionDate END DESC
If I apply order by clause outside the stored procedure it works fine but inside the sp it didn't work (applying order by desc on TransactionDate not working)

Try creating your stored procedure like below then
DELIMITER //
CREATE PROCEDURE select_whatever(sortField VARCHAR(20), sortDirection CHAR(4))
BEGIN
DECLARE select_clause TEXT;
DECLARE order_by_clause VARCHAR(100);
SET select_clause = "
select
tr.TransactionId as TxnIdentifier,
m.MerchantName as MerchantName,
case
when tr.ChannelType=2 then 'ACH'
when tr.ChannelType=3 then 'CC'
when tr.ChannelType=4 then 'Debit'
else null
end as ChannelType,
tr.CaptureAmount as CaptureAmount,
case
when tr.OperationType=0 then 'Sale'
when tr.OperationType=1 then 'Verify only'
when tr.OperationType=2 then 'ForceSale'
when tr.OperationType=3 then 'Adjust'
when tr.OperationType=4 then 'Activate'
when tr.OperationType=5 then 'Deactivate'
when tr.OperationType=6 then 'Reload'
when tr.OperationType=7 then 'Refund'
when tr.OperationType=8 then 'Inquire'
else null
end as TxnType,
case
when tr.TransactionStatus=0 then 'Created'
when tr.TransactionStatus=1 then 'Pending'
when tr.TransactionStatus=2 then 'Authorized'
when tr.TransactionStatus=3 then 'Posted'
when tr.TransactionStatus=4 then 'Accepted'
when tr.TransactionStatus=5 then 'Failed'
when tr.TransactionStatus=6 then 'Returned'
when tr.TransactionStatus=7 then 'Chargeback'
when tr.TransactionStatus=8 then 'Void'
when tr.TransactionStatus=9 then 'Refunded'
when tr.TransactionStatus=10 then 'Approved'
when tr.TransactionStatus=11 then 'Void attempted'
when tr.TransactionStatus=12 then 'Refund attempted'
when tr.TransactionStatus=13 then 'Hold'
when tr.TransactionStatus=14 then 'Denied'
when tr.TransactionStatus=15 then 'Settlement hold'
when tr.TransactionStatus=16 then 'Success'
when tr.TransactionStatus=17 then 'Retried'
when tr.TransactionStatus=100 then 'Unknown'
else null
end as TxnStatus,
tr.PreAuthCode as AuthCode,
DATE_FORMAT(tr.TransactionDate, '%m-%d-%Y %H:%i:%s') as TransactionDate,
case
when tr.OperationType='7' then tr.Amount
else null
end as RefundAmount,
case
when tr.OperationType='7'
then DATE_FORMAT(tr.TransactionDate, '%m-%d-%Y %H:%i:%s')
else null
end as RefundedOn,
tr.TraceNumber as TraceNumber
from TransactionEntity tr
inner join `enter code here`DOMAIN.Merchant m on m.Id=tr.MerchantId where 1=1
and (tr.MerchantId = merchantId or merchantId=0)
and (tr.ChannelType = channelType or channelType=0)
And (tr.TransactionDate >= startDate or startDate is null)
And (tr.TransactionDate <= endDate or endDate is null)
";
SET order_by_clause = "ORDER BY";
IF sortField = "TransactionDate" AND sortDirection="ASC" THEN
SET order_by_clause = CONCAT(order_by_clause, " TransactionDate ASC")
ELSEIF sortField = "TransactionDate" AND sortDirection="DESC" THEN
SET order_by_clause = CONCAT(order_by_clause, " TransactionDate DESC")
END IF
SET #dynamic_sql = CONCAT(select_clause, ' ', order_by_clause);
PREPARE select_whatever_statement
FROM #dynamic_sql;
EXECUTE select_whatever_statement;
DEALLOCATE PREPARE select_whatever_statement;
END //
DELIMITER ;

Related

EMBEDDED DATEDIFF EXCLUD WEEKENDS + CASE STATEMENT

I have the below query that utilizes a case statement. I would like to datediff two dates but exclude weekend days.
I have the below that excutes but now I would like to exclude Sat and Sunday from this... AND DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate) <= 2
CASE WHEN
S.Name IN ('Assessment','Survey')
AND A.ALERT_DESC = 'ER'
AND CAST(A.ALERTS_CREATE_DT AS DATE) <= CAST(S.CreatedDate AS DATE)
AND DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate) <= 2 /*EXCLUDE Sat and Sunday from the calculation*/
Full Query
SELECT
CASE WHEN
S.Name IN ('Assessment','Survey')
AND A.ALERT_DESC = 'ER'
AND CAST(A.ALERTS_CREATE_DT AS DATE) <= CAST(S.CreatedDate AS DATE)
AND
( DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate) <= 2 /*Business Days*/
--DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate) + 1
---(DATEDIFF(WK,A.ALERTS_CREATE_DT,S.CreatedDate) * 2)
---(CASE WHEN DATENAME(DW,A.ALERTS_CREATE_DT) = 'SUNDAY' THEN 1 ELSE 0 END)
---(CASE WHEN DATENAME(DW,S.CreatedDate) = 'SATURADAY' THEN 1 ELSE 0 END)
)
THEN 'Y'
WHEN A.ALERT_DESC = 'model' OR S.CreatedDate IS NULL OR S.Name = 'ER'
THEN ''
ELSE 'N'
END 'Count towards Alerts'
FROM A
FULL S ON A.id= S.id
WHERE 1=1
This should give you the required result by excluding the Saturdays and Sundays.
SELECT A.ALERT_DESC,A.ALERTS_CREATE_DT,S.Name,S.CreatedDate,
CASE WHEN
S.Name IN ('Assessment','Survey') AND A.ALERT_DESC = 'ER'
AND CAST(A.ALERTS_CREATE_DT AS DATE) <= CAST(S.CreatedDate AS DATE)
AND
(( DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate)+1
- (datediff(wk,A.ALERTS_CREATE_DT,S.CreatedDate)*2)
- case when datepart(dw,A.ALERTS_CREATE_DT)=1 then 1 else 0 end
- case when datepart(dw,S.CreatedDate)=7 then 1 else 0 end
)) <=2 THEN 'Y'
WHEN A.ALERT_DESC = 'model' OR S.CreatedDate IS NULL OR S.Name = 'ER' THEN ''
ELSE 'N' END 'Count towards Alerts'
FROM A,S

Doing an Update in SQL, with a CASE WHEN Statement

What I want to know, is it somehow possible to do an update to a table, in a Case statement? Or if there is Some way to do this? I have a button to pull a report (this button goes and calls a stored procedure, and it gets a list of columns and their residing columns).
I basically want to update the table, IF, and only IF, the DateClosed column is NULL AND ClosedBy is null (i.e., the end date was reached, so the campaign is CLOSED).
The way I usually determine if the campaign is closed, is by doing Checks on the start and end date. Ie When EndDate < GetDate() Then "Closed". So obviously that displays correctly, but my database displays null because there was no update.
This is my stored procedure:
ALTER PROCEDURE [dbo].[sp_CampaignStats]
#from DATETIME,
#to DATETIME
AS
SELECT
CampaignName AS 'CAMPAIGN NAME',
CampaignDescription AS 'CAMPAIGN DESCRIPTION',
CASE
WHEN EndDate >= GETDATE() AND StartDate <= GETDATE() THEN 'Active'
WHEN StartDate >= GETDATE() THEN 'Pending'
WHEN CampaignStatus = 4 THEN 'Archived'
ELSE 'Closed'
END as 'CurrentStatus',
CONVERT(VARCHAR(11), StartDate, 106) + ' - ' + CONVERT(VARCHAR(11), EndDate, 106) AS 'CAMPAIGN DATES',
Discount AS 'DISCOUNT',
[Target] AS 'TARGET',
Uptake AS 'UPTAKE',
tc.DateAdded as 'DATE ADDED',
U.FirstName + ' ' + u.LastName As 'ADDED BY',
CASE
WHEN CloseBy IS NULL AND EndDate < GETDATE() AND CloseBy = Null THEN 'System'
WHEN CampaignStatus = 4 THEN 'Archived'
WHEN CloseBy IS not Null THEN UU.FirstName + ' ' + uu.LastName
ELSE 'Not Closed'
END AS 'CLOSED BY',
DateClosed AS 'DATE CLOSED'
FROM
Tbl_Campaign tc
LEFT JOIN
tbl_User U ON Tc.AddedBy = U.UserId
LEFT JOIN
Tbl_User UU ON TC.CloseBy = UU.UserId
WHERE
(startDate >= #from OR enddate <= #to)
AND CampaignStatus IN (1, 2, 3, 4)
So you want to update your table before the SELECT happens?
Try something like this:
UPDATE dbo.Tbl_Campaign
SET -- what do you want to update to what value here????
WHERE
DateClosed IS NULL
AND ClosedBy IS NULL
Or what exactly are you trying to do?? You're still being rather unclear and vague in your question - you're not mentioning WHAT column in WHICH table you want to update to WHAT value if that condition is met.....
SQL only allows one operation per statement. SELECTs only read data, UPDATEs only write data.
If I've understood your problem though, you've got a NULL in an end date field that's preventing you from displaying your button correctly? If that's the case, you could do something like
SELECT
StatusDate =
CASE WHEN EndDate < GETDATE() THEN 'Closed'
WHEN EndDate > GETDATE() THEN 'Open'
WHEN EndDate IS NULL THEN 'End Date not set'
END
FROM
SourceTable
Or, if it was easier in your code, wrap the CASE in an ISNULL or COALESCE function that can be used to fill in the default value.
None of these will update the table on the read, but they'll all stop the NULL from preventing your read returning anything at all.
Seeing your actual code now, what you want is something like this -
ALTER PROCEDURE [dbo].[usp_CampaignStats]
#from DATETIME,
#to DATETIME
AS
SET NOCOUNT ON;
--Make sure any NULLs we need to have been cleaned up
UPDATE Tbl_Campaign
SET <Fields>
WHERE DateClosed IS NULL AND ClosedBy IS NULL
AND (startDate >= #from OR enddate <= #to)
AND CampaignStatus IN (1, 2, 3, 4);
--Now return the data
SELECT
CampaignName AS 'CAMPAIGN NAME',
CampaignDescription AS 'CAMPAIGN DESCRIPTION',
CASE
WHEN EndDate >= GETDATE() AND StartDate <= GETDATE() THEN 'Active'
WHEN StartDate >= GETDATE() THEN 'Pending'
WHEN CampaignStatus = 4 THEN 'Archived'
ELSE 'Closed'
END as 'CurrentStatus',
CONVERT(VARCHAR(11), StartDate, 106) + ' - ' + CONVERT(VARCHAR(11), EndDate, 106) AS 'CAMPAIGN DATES',
Discount AS 'DISCOUNT',
[Target] AS 'TARGET',
Uptake AS 'UPTAKE',
tc.DateAdded as 'DATE ADDED',
U.FirstName + ' ' + u.LastName As 'ADDED BY',
CASE
WHEN CloseBy IS NULL AND EndDate < GETDATE() AND CloseBy = Null THEN 'System'
WHEN CampaignStatus = 4 THEN 'Archived'
WHEN CloseBy IS not Null THEN UU.FirstName + ' ' + uu.LastName
ELSE 'Not Closed'
END AS 'CLOSED BY',
DateClosed AS 'DATE CLOSED'
FROM
Tbl_Campaign tc
LEFT JOIN
tbl_User U ON Tc.AddedBy = U.UserId
LEFT JOIN
Tbl_User UU ON TC.CloseBy = UU.UserId
WHERE
(startDate >= #from OR enddate <= #to)
AND CampaignStatus IN (1, 2, 3, 4);

Creating function error sql server 2008

I want to create a fucntion, but getting error.
below is query:
CREATE FUNCTION WFSlaTimer
(
#OBJECT_PK_ID INT = 110
)
RETURNS TABLE
AS BEGIN
DECLARE
#TIMER_START_ACTIVITY_ID INT,
#TIMER_START_ACTIVITY_COMPLETED_ON DATETIME,
#TIMER_END_ACTIVITY_ID INT,
#TIMER_END_ACTIVITY_COMPLETED_ON DATETIME,
#SLA_TIME_SCHEDULE_IN_DAYS INT,
#SLA_DISPLAY VARCHAR(20),
#START_DATE DATETIME,
#END_DATE DATETIME,
#BUSINESS_START_TIME VARCHAR(10),
#BUSINESS_END_TIME VARCHAR(10),
#BUSINESS_HOURS INT,
#SLA_CUT_OFF_TIME VARCHAR(10),
#IS_OBJECT_STATUS_IS_TERMINAL INT,
#COMPLETED_ACTION_ID INT,
#UNCHECKED_ACTION_ID INT,
#DAY_ADDED INT
SELECT #IS_OBJECT_STATUS_IS_TERMINAL = CASE when wos.FLG_STATUS_TYPE = 'W' THEN 0 ELSE 1 END
FROM WF.WF_OBJECT_INSTANCE woi
INNER JOIN WF.WF_OBJECT_STATUS wos ON wos.OBJECT_STATUS_ID = woi.OBJECT_STATUS_ID
WHERE woi.LINK_PK_ID = #OBJECT_PK_ID
SET #SLA_TIME_SCHEDULE_IN_DAYS = (SELECT CASE WHEN s.SLA_SCHEDULE_ID = 1 THEN lr.RUSH_NO_OF_DAYS ELSE s.NUM_OF_DAYS END --1= [RUSH]
FROM loan.LOAN_REQUEST lr
INNER JOIN WF.WF_SLA_SCHEDULE s
ON s.SLA_SCHEDULE_ID = ISNULL(lr.SLA_SCHEDULE_ID, 2) --{2= SLA-Schedule 5 Days}
WHERE lr.LOAN_REQUEST_ID = #OBJECT_PK_ID)
SET #SLA_DISPLAY = (SELECT
CASE WHEN s.SLA_SCHEDULE_ID = 1 THEN s.DISPLAY_NAME + ' (' + CAST(lr.RUSH_NO_OF_DAYS AS VARCHAR) + ')' ELSE s.DISPLAY_NAME END --1= [RUSH]
FROM loan.LOAN_REQUEST lr
INNER JOIN WF.WF_SLA_SCHEDULE s
ON s.SLA_SCHEDULE_ID = ISNULL(lr.SLA_SCHEDULE_ID, 2) --{2= SLA-Schedule 5 Days}
WHERE lr.LOAN_REQUEST_ID = #OBJECT_PK_ID)
SET #BUSINESS_START_TIME = (SELECT s.CONFIG_VALUE FROM SYS_CONFIG_ENTRY s WHERE s.NAME = 'BUSINESS_START_TIME')
SET #BUSINESS_END_TIME = (SELECT s.CONFIG_VALUE FROM SYS_CONFIG_ENTRY s WHERE s.NAME = 'BUSINESS_END_TIME')
SET #BUSINESS_HOURS = (SELECT CAST(DATEDIFF(hour, CAST(#BUSINESS_START_TIME AS DATETIME), CAST(#BUSINESS_END_TIME AS DATETIME)) AS INT))
SET #SLA_CUT_OFF_TIME = (SELECT DATEPART(hour, CAST(s.CONFIG_VALUE AS TIME)) FROM SYS_CONFIG_ENTRY s WHERE s.NAME = 'SLA_CUT_OFF_TIME')
SET #COMPLETED_ACTION_ID = (SELECT ACTION_TYPE_ID FROM WF.WF_ACTION_TYPE WHERE NAME = 'ACTIVITY_COMPLETED')
SET #UNCHECKED_ACTION_ID = (SELECT ACTION_TYPE_ID FROM WF.WF_ACTION_TYPE WHERE NAME = 'ACTIVITY_UNCHECKED')
--GET SLA TIMER ACTIVITY IDs
SELECT #TIMER_START_ACTIVITY_ID = t.START_ACTIVITY_ID,
#TIMER_END_ACTIVITY_ID = t.END_ACTIVITY_ID
FROM [WF].WF_TIMER t
WHERE t.NAME = 'SLA_TIMER'
--Get START ACTIVITY ON
SELECT #TIMER_START_ACTIVITY_COMPLETED_ON = ACTION_ON
FROM [WF].WF_OBJECT_ACTIVITY_HISTORY woah
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND woah.ACTIVITY_ID = #TIMER_START_ACTIVITY_ID
AND ACTION_ID = #COMPLETED_ACTION_ID
AND
--{
woah.APPLICATION_HISTORY_ID > ISNULL((SELECT TOP 1 ISNULL(APPLICATION_HISTORY_ID, 0)
FROM WF.WF_OBJECT_ACTIVITY_HISTORY
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND ACTIVITY_ID = #TIMER_START_ACTIVITY_ID
AND ACTION_ID = #UNCHECKED_ACTION_ID
ORDER BY ACTION_ON DESC
), 0)
--}
--AND
----{
--0 = ISNULL((SELECT TOP 1 ISNULL(APPLICATION_HISTORY_ID, 0)
-- FROM WF.WF_OBJECT_ACTIVITY_HISTORY
-- WHERE LINK_PK_ID = #OBJECT_PK_ID
-- AND ACTIVITY_ID = #TIMER_END_ACTIVITY_ID
-- AND ACTION_ID = #COMPLETED_ACTION_ID
-- ORDER BY ACTION_ON DESC), 0)
----}
ORDER BY ACTION_ON DESC
--Get END ACTIVITY ON
SELECT #TIMER_END_ACTIVITY_COMPLETED_ON = ACTION_ON
FROM [WF].WF_OBJECT_ACTIVITY_HISTORY woah
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND woah.ACTIVITY_ID = #TIMER_END_ACTIVITY_ID
AND ACTION_ID = #COMPLETED_ACTION_ID
AND
--{
woah.APPLICATION_HISTORY_ID > ISNULL((SELECT TOP 1 ISNULL(APPLICATION_HISTORY_ID, 0)
FROM WF.WF_OBJECT_ACTIVITY_HISTORY
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND ACTIVITY_ID = #TIMER_END_ACTIVITY_ID
AND ACTION_ID = #UNCHECKED_ACTION_ID
ORDER BY ACTION_ON DESC
), 0)
--}
ORDER BY ACTION_ON DESC
--TO DO
--SET #TIMER_START_ACTIVITY_COMPLETED_ON = '2014-05-15 02:40:21.100'
--SET #TIMER_END_ACTIVITY_COMPLETED_ON = '2014-05-14 12:40:21.100'
SET #START_DATE = #TIMER_START_ACTIVITY_COMPLETED_ON
SET #DAY_ADDED = #SLA_TIME_SCHEDULE_IN_DAYS -- SLA Schedule Days
+ CASE WHEN DATEPART(hour, #TIMER_START_ACTIVITY_COMPLETED_ON) >= #SLA_CUT_OFF_TIME THEN 0 ELSE -1 END -- SLA Cut Off Time
SET #END_DATE = #START_DATE + #DAY_ADDED
--Exclud Holidays
--{
DECLARE #START_ON_DATE DATETIME = CAST(#START_DATE AS DATE)
WHILE #DAY_ADDED > 0
BEGIN
SELECT #END_DATE = #START_ON_DATE + #DAY_ADDED
--COUNT NO OF HOLIDAYS IF FALLING WITHIN START-DATE AND END-DATE
SELECT #DAY_ADDED = COUNT(*) FROM [WF].WF_CALENDAR WC --HOLIDAY LIST
WHERE WC.DATE BETWEEN #START_ON_DATE+1 AND #END_DATE AND (WC.IS_WEEKEND = 1 OR WC.IS_HOLIDAY = 1)
SET #START_ON_DATE = #END_DATE
END
--}
SET #END_DATE = (CAST(CAST(CAST(#END_DATE AS DATE) AS DATETIME) + CAST(#BUSINESS_END_TIME AS TIME) AS DATETIME))
;WITH TIMER_CTE AS (
SELECT #START_DATE AS OBJECT_CREATED_ON,
#END_DATE AS OBJECT_END_ON,
DIFFERENCE_IN_DAYS = DATEDIFF(dd, GETDATE(), #END_DATE),
TODAY_REMAINING_MINUTES =
CASE WHEN CONVERT(VARCHAR(10), #END_DATE, 112) >= CONVERT(VARCHAR(10), GETDATE(), 112)
THEN DATEDIFF(minute, GETDATE(), (CAST(CAST(CAST(GETDATE() AS DATE) AS DATETIME) + CAST(#BUSINESS_END_TIME AS TIME) AS DATETIME)))
ELSE 0 END,
TODAY_REMAINING_HOURS =
CASE WHEN CONVERT(VARCHAR(10), #END_DATE, 112) >= CONVERT(VARCHAR(10), GETDATE(), 112)
THEN (DATEDIFF(minute, GETDATE(), (CAST(CAST(CAST(GETDATE() AS DATE) AS DATETIME) + CAST(#BUSINESS_END_TIME AS TIME) AS DATETIME)))/60)
ELSE 0 END
)
RETURN (
SELECT
IS_SHOW_SLA = CASE WHEN #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
--OR #IS_OBJECT_STATUS_IS_TERMINAL = 1
--OR #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
THEN 0
ELSE 1 END,
#START_DATE AS [START_DATE], #END_DATE AS [END_DATE],
SLA_TYPE = #SLA_DISPLAY,
SLA_DUE = CONVERT(VARCHAR(10), CONVERT(DATETIME, tc.OBJECT_END_ON, 1), 101),
#BUSINESS_END_TIME AS BUSINESS_END_TIME,
SLA_START_ACTIVITY_CHECKED_ON = tc.OBJECT_CREATED_ON,
SLA_END_ACTIVITY_CHECKED_ON = #TIMER_END_ACTIVITY_COMPLETED_ON,
SLA_MISSED = CASE WHEN
--TODAY_REMAINING_MINUTES <= 0
--AND CONVERT(VARCHAR(10), #END_DATE, 112) = CONVERT(VARCHAR(10), GETDATE(), 112)
--OR
( GETDATE()> #END_DATE)
OR #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
THEN 'Missed' ELSE NULL END,
tc.TODAY_REMAINING_HOURS,
tc.TODAY_REMAINING_MINUTES,
LAST_DAY_TIME_REMAINING =
CASE
WHEN #TIMER_END_ACTIVITY_COMPLETED_ON <= #END_DATE THEN 'Successful Completed'
WHEN CONVERT(VARCHAR(10), #END_DATE, 112) = CONVERT(VARCHAR(10), GETDATE(), 112)
THEN
CASE WHEN
tc.TODAY_REMAINING_HOURS <=0 AND tc.TODAY_REMAINING_MINUTES > 0 THEN
CASE WHEN tc.TODAY_REMAINING_MINUTES = 1 THEN CAST(tc.TODAY_REMAINING_MINUTES AS VARCHAR) + ' min remaining'
ELSE CAST(tc.TODAY_REMAINING_MINUTES AS VARCHAR) + ' mins remaining' END
WHEN tc.TODAY_REMAINING_HOURS =1 THEN CAST(tc.TODAY_REMAINING_HOURS AS VARCHAR) + ' hour remaining'
WHEN tc.TODAY_REMAINING_HOURS >1 THEN CAST(tc.TODAY_REMAINING_HOURS AS VARCHAR) + ' hours remaining'
ELSE NULL
END
ELSE NULL
END,
REMAINING_DAYS = CASE WHEN tc.DIFFERENCE_IN_DAYS <=0 THEN '0 day'
WHEN tc.DIFFERENCE_IN_DAYS > 1 THEN CAST(tc.DIFFERENCE_IN_DAYS AS VARCHAR) + ' days '
ELSE CAST(tc.DIFFERENCE_IN_DAYS AS VARCHAR) + ' day ' END
FROM TIMER_CTE tc
)
END;
GO
I am getting this error:
Msg 156, Level 15, State 1, Procedure WFSlaTimer, Line 144
Incorrect syntax near the keyword 'RETURN'.
Msg 178, Level 15, State 1, Procedure WFSlaTimer, Line 144
A RETURN statement with a return value cannot be used in this context.
Msg 102, Level 15, State 31, Procedure WFSlaTimer, Line 189
Incorrect syntax near 'BEGIN'.
Any help please
There are two kind of function that return table. the inline function and multi-statement function. Yours is multi-statement. Here is the syntax for this:
--Transact-SQL Multistatement Table-valued Function Syntax
CREATE FUNCTION [ schema_name. ] function_name
( [ { #parameter_name [ AS ] [ type_schema_name. ] parameter_data_type
[ = default ] [READONLY] }
[ ,...n ]
]
)
RETURNS #return_variable TABLE <table_type_definition>
[ WITH <function_option> [ ,...n ] ]
[ AS ]
BEGIN
function_body
RETURN
END
[ ; ]
For more information refer to CREATE FUNCTION (Transact-SQL) BOL documentation.
You have to define the returned table's structure (fields and data types)
1) Add a variable name to the function definition (#tableVariable in the above example).
2) Fill the table definition (columns and datatypes)
3) Modify your function to insert the result into the defined table variable, then use an empty RETURN statement when the function should return.
1st step
CREATE FUNCTION WFSlaTimer
(
#OBJECT_PK_ID INT = 110
)
RETURNS #tableVariable TABLE (
IS_SHOW_SLA INT,
StartDate DATETIME2,
EndDate DATETIME2
/** List all of your returned columns like when you creating a table **/
)
AS
BEGIN
/** Do your stuff **/
INSERT INTO #tableVariable ( /* field list */) VALUES (/* value list */)
-- OR --
INSERT INTO #tableVariable ( /* field list */)
SELECT /* FieldList */ FROM myCTE
RETURN
END
2nd step
Modify your RETURN () statement like this:
INSERT INTO #tableVanriable (IS_SHOW_SLA , StartDate , EndDate)
SELECT
IS_SHOW_SLA = CASE WHEN #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
--OR #IS_OBJECT_STATUS_IS_TERMINAL = 1
--OR #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
THEN 0
ELSE 1 END,
#START_DATE AS [START_DATE], #END_DATE AS [END_DATE],
SLA_TYPE = #SLA_DISPLAY
/** .... **/
FROM TIMER_CTE tc
/** 3rd step **/
RETURN

Error in last line near end

While i Execute a stored procedure I don't know why showing error in last line...
I can't find any error with it
The error is telling
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '' at
line 60
_
CREATE PROCEDURE `PartyBalanceViewByLedgerId`
(
p_ledgerId varchar(50),
p_crOrDr varchar(50),
p_branchId varchar(50)
)
BEGIN
IF (p_crOrDr='Dr')
THEN
SELECT
TEMP.voucherNo +'_'+ TEMP.voucherType AS ID,
TEMP.voucherType,
CASE WHEN (TEMP.voucherType = 'Receipt Voucher')
THEN
(SELECT receiptMasterId FROM tbl_ReceiptMaster
WHERE (receiptMasterId = TEMP.voucherNo))
ELSE
(SELECT purchaseMasterId FROM tbl_PurchaseMaster
WHERE (purchaseMasterId = TEMP.voucherNo))
END AS voucherNo,
CAST(CAST(TEMP.balance AS DECIMAL(24,2)) AS char(27))
AS amount
FROM(SELECT
A.voucherNo,
A.voucherType,
(SUM(ifnull(A.credit, 0)) - SUM(ifnull(A.debit, 0)))
AS balance
FROM tbl_PartyBalance AS A
WHERE (A.voucherType = 'Purchase Invoice'
OR A.voucherType = 'Receipt Voucher')
AND A.ledgerId=p_ledgerId
AND A.branchId=p_branchId
AND A.optional='False'
GROUP BY A.voucherNo,A.voucherType
)AS TEMP
WHERE TEMP.Balance>0 ;
ELSE
SELECT
TEMP.voucherNo +'_'+ TEMP.voucherType ID,
TEMP.voucherType,
CASE WHEN TEMP.voucherType = 'Payment Voucher' THEN
(SELECT paymentMasterId FROM tbl_PaymentMaster WHERE (paymentMasterId = TEMP.voucherNo))
ELSE
(SELECT salesInvoiceNo FROM tbl_SalesMaster WHERE (salesMasterId = TEMP.voucherNo)) END AS voucherNo,
CAST(CAST(TEMP.balance AS DECIMAL(24,2))AS char(27)) AS amount
FROM(
SELECT
A.voucherNo,
A.voucherType,
(SUM(ifnull(A.debit, 0)) - SUM(ifnull(A.credit,0))) AS balance
FROM tbl_PartyBalance AS A
WHERE (A.voucherType = 'Sales Invoice' OR A.voucherType = 'Payment Voucher'OR A.voucherType = 'Job Invoice') AND A.ledgerId=p_ledgerId AND A.branchId=p_branchId AND A.optional='False'
GROUP BY A.voucherNo,A.voucherType
)AS TEMP
WHERE TEMP.Balance > 0 ;
END
try with this i have update some changes END IF and ; etc
CREATE PROCEDURE `PartyBalanceViewByLedgerId`
(
p_ledgerId varchar(50),
p_crOrDr varchar(50),
p_branchId varchar(50)
)
BEGIN
IF (p_crOrDr='Dr')
SELECT
TEMP.voucherNo +'_'+ TEMP.voucherType AS ID,
TEMP.voucherType,
CASE WHEN (TEMP.voucherType = 'Receipt Voucher')
THEN
(SELECT receiptMasterId FROM tbl_ReceiptMaster
WHERE (receiptMasterId = TEMP.voucherNo))
ELSE
(SELECT purchaseMasterId FROM tbl_PurchaseMaster
WHERE (purchaseMasterId = TEMP.voucherNo))
END AS voucherNo,
CAST(CAST(TEMP.balance AS DECIMAL(24,2)) AS char(27))
AS amount
FROM(SELECT
A.voucherNo,
A.voucherType,
(SUM(ifnull(A.credit, 0)) - SUM(ifnull(A.debit, 0)))
AS balance
FROM tbl_PartyBalance AS A
WHERE (A.voucherType = 'Purchase Invoice'
OR A.voucherType = 'Receipt Voucher')
AND A.ledgerId=p_ledgerId
AND A.branchId=p_branchId
AND A.optional='False'
GROUP BY A.voucherNo,A.voucherType
)AS TEMP
WHERE TEMP.Balance>0;
ELSE
SELECT
TEMP.voucherNo +'_'+ TEMP.voucherType ID,
TEMP.voucherType,
CASE WHEN TEMP.voucherType = 'Payment Voucher' THEN
(SELECT paymentMasterId FROM tbl_PaymentMaster WHERE (paymentMasterId = TEMP.voucherNo))
ELSE
(SELECT salesInvoiceNo FROM tbl_SalesMaster WHERE (salesMasterId = TEMP.voucherNo)) END AS voucherNo,
CAST(CAST(TEMP.balance AS DECIMAL(24,2))AS char(27)) AS amount
FROM(
SELECT
A.voucherNo,
A.voucherType,
(SUM(ifnull(A.debit, 0)) - SUM(ifnull(A.credit,0))) AS balance
FROM tbl_PartyBalance AS A
WHERE (A.voucherType = 'Sales Invoice' OR A.voucherType = 'Payment Voucher'OR A.voucherType = 'Job Invoice') AND A.ledgerId=p_ledgerId AND A.branchId=p_branchId AND A.optional='False'
GROUP BY A.voucherNo,A.voucherType
)AS TEMP
WHERE TEMP.Balance > 0 ;
END IF;
END;
Are you using a DELIMITER? If not pl go through this description:
Delimiters in MySQL
I hope this will solve your problem.
Remove the semicolon before ELSE in :
GROUP BY A.voucherNo,A.voucherType
)AS TEMP
WHERE TEMP.Balance>0
ELSE
SELECT
TEMP.voucherNo +'_'+ TEMP.voucherType ID,
TEMP.voucherType,

Mysql Function returning same value

I am in need of mysql function but gives same value every time
this mysql function gives me same value every time i.e. S_Start_ToBeStarted (Value of 1st If)
-- colorA
DELIMITER $$
DROP FUNCTION IF EXISTS `colorA`$$
CREATE FUNCTION `colorA`(
Appf VARCHAR(3),
Start_Datef DATETIME,
PDCf DATETIME
) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE finalcolor INT DEFAULT 0;
IF Appf = 'Yes' & IFNULL(Start_Datef, 'NULL' = 'NULL' & sysdate() <= PDCf
THEN SET finalcolor = (SELECT `PP_Colors`.`S_Start_ToBeStarted` FROM `SCR_Sap`.`PP_Colors` LIMIT 1);
ELSE IF Appf = 'Yes' & IFNULL(Start_Datef, 'NULL') = 'NULL' & sysdate() > PDCf
THEN SET finalcolor = (SELECT `PP_Colors`.`S_Start_Error` FROM `SCR_Sap`.`PP_Colors` LIMIT 1);
ELSE IF Appf = 'Yes' & IFNULL(Start_Datef, 'NULL') != 'NULL' & sysdate() <= PDCf
THEN SET finalcolor = (SELECT `PP_Colors`.`S_Start_Ok` FROM `SCR_Sap`.`PP_Colors` LIMIT 1);
ELSE IF Appf = 'Yes' & IFNULL(Start_Datef, 'NULL') != 'NULL' & sysdate() > PDCf
THEN SET finalcolor = (SELECT `PP_Colors`.`S_Start_LateStarted` FROM `SCR_Sap`.`PP_Colors` LIMIT 1);
ELSE SET finalcolor = (SELECT `PP_Colors`.`S_NotApplicable` FROM `SCR_Sap`.`PP_Colors` LIMIT 1);
END IF;
END IF;
END IF;
END IF;
RETURN finalcolor;
END$$
DELIMITER ;
Null doesn't work well with = and != operators, the result of foobar=NULL is NULL (unknown) not true or false. Use IS NULL and IS NOT NULL instead