I'm trying to figure out how to flip this from a table format to a column format.
Hi, I know how to create a SQL HTML Email via table format: i.e
Customer Address City
Joe 123 Here Oakland
but i need to be able to flip this to look like
Customer: Joe
Address: 123 Here
City: Oakland
I'm using SQL 2012
Any help would be appreciated
Please advise
DECLARE #xmlinv NVARCHAR(MAX);
DECLARE #bodyinv NVARCHAR(MAX);
DECLARE #trrowinv NVARCHAR(MAX);
DECLARE #tempemaillistinv NVARCHAR(MAX);
DECLARE #subject_anomaly NVARCHAR(MAX);
SET #subject_anomaly
= N'Inventory Adjustments ' + CAST(#COUNTSinv AS VARCHAR(3)) + N' '
+ LEFT(CONVERT(VARCHAR(10), GETDATE(), 101), 3) + SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 101), 4, 3)
+ RIGHT(CONVERT(VARCHAR(10), GETDATE(), 101), 2);
SET #xmlinv
= CAST(
(
SELECT T4.product AS 'td',
'',
T4.available AS 'td',
'',
CASE
WHEN T4.quarantine IS NULL THEN
0
ELSE
T4.quarantine
END AS 'td',
'',
CASE
WHEN T4.labels IS NULL THEN
0
ELSE
T4.labels
END AS 'td',
'',
T4.MinLog AS 'td',
'',
T.available AS 'td',
'',
CASE
WHEN T.quarantine IS NULL THEN
0
ELSE
T.quarantine
END AS 'td',
'',
CASE
WHEN T.labels IS NULL THEN
0
ELSE
T.labels
END AS 'td',
'',
T.MinLog AS 'td'
--SELECT T4.product,T4.available,T4.quarantine,T4.labels,T4.MinLog,T.available,T.quarantine,T.labels,T.MinLog
FROM #t4 AS T4
LEFT OUTER JOIN #t3 AS T3
ON T4.MaxRow2 = T3.MaxRow
AND T4.product = T3.product
LEFT OUTER JOIN #t2 AS T2
ON T4.MaxRow2 = T2.MaxRow
AND T4.product = T2.product
LEFT OUTER JOIN #temp AS T
ON T4.MaxRow2 = T.therow + 1
AND T4.product = T.product
ORDER BY 1
--ORDER BY 1,3 desc
FOR XML PATH('tr'), ELEMENTS
)
AS
NVARCHAR(MAX));
SET #bodyinv
= N'<html><H2>Adjustments</H2><body bgcolor=white><table border=1 style=''border:1px;background-color:#FFFFCC;bordercolor:#FFCC00'' cellpadding=''1'' cellspacing=''0''>';
SET #trrowinv
= N'<tr><th>Product</th><th>NewAvailable</th><th>NewQuarantine</th><th>NewLabels</th><th>LastUpdate</th><th>OldAvailable</th><th>OldQuarantine</th><th>OldLabels</th><th>PriorUpdate</th></tr>';
SET #bodyinv = #bodyinv + #trrowinv + #xmlinv + N'</table></body></html>';
SET #tempemaillistinv = N'abc#abc.com';
EXEC [msdb].[dbo].[sp_send_dbmail] #recipients = #tempemaillistinv,
#body = #bodyinv,
#body_format = 'HTML',
#subject = #subject_anomaly,
#profile_name = 'abc';
Related
I am using a condition to lock the login account after a fixed number of attempts with the wrong password. The update portion is as follows :
loginAttempts (INT(1)) is read from login account first
DECLARE LoginAttempts INT(1);
UPDATE login SET
LOGIN_ACCOUNT_STATUS = (SELECT CASE (LoginAttempts > MaxLoginAttempts) WHEN 1 THEN 'LOCKED' ELSE 'ACTIVE' END),
LOGIN_LOGIN_ATTEMPTS = (SELECT CASE (#USER_FOUND AND #PASSWORD_CORRECT) WHEN 1 THEN 0 ELSE LOGIN_LOGIN_ATTEMPTS + 1 END),
LOGIN_LAST_LOGIN_DATE = (SELECT CASE (#USER_FOUND AND #PASSWORD_CORRECT) WHEN 1 THEN TransactionDateTime ELSE LOGIN_LAST_LOGIN_DATE END),
LOGIN_LAST_LOGIN_LOCATION = null
WHERE LOGIN_EMAIL = UserEmail;
When I set MaxLoginAttmpts at 5, the account gets locked at 11 (Greater than twice maxLoginAttempts).
If I set MaxLoginAttmpts at 2, the account gets locked at 5 (Greater than twice maxLoginAttempts).
Why is this ? Any help is appreciated.
Here I am adding the full stored procedure.
CREATE DEFINER=`pubuducg`#`%` PROCEDURE `CustomerAuthenticate`(IN UserEmail VARCHAR(100), IN PassWD VARCHAR(40), IN AccStatus VARCHAR(100),IN TransactionDateTime DATETIME, IN MaxLoginAttempts INT(1))
BEGIN
DECLARE LoginUserID INT(11);
DECLARE LoginEmail VARCHAR(50);
DECLARE LoginPassword TINYTEXT;
DECLARE LoginAttempts INT(1);
DECLARE AccountStatus VARCHAR(45);
DECLARE UserRoles VARCHAR(80);
SELECT
login.LOGIN_USER_ID,
login.LOGIN_EMAIL,
login.LOGIN_PASSWORD,
login.LOGIN_ACCOUNT_STATUS,
login.LOGIN_LOGIN_ATTEMPTS,
GROUP_CONCAT(user_role.USER_ROLE_ROLE SEPARATOR ',') AS ROLES
INTO
LoginUserID,
LoginEmail,
LoginPassword,
AccountStatus,
LoginAttempts,
UserRoles
FROM login
INNER JOIN user_role ON
user_role.USER_ROLE_USER_ID = login.LOGIN_USER_ID AND user_role.USER_ROLE_STATUS = AccStatus
WHERE login.LOGIN_EMAIL = UserEmail;
SET #USER_FOUND = found_rows();
SET #PASSWORD_CORRECT = IF((LoginPassword = PassWD AND AccountStatus = AccStatus), true, false);
UPDATE login SET
LOGIN_ACCOUNT_STATUS = (SELECT CASE (LoginAttempts > MaxLoginAttempts) WHEN 1 THEN 'LOCKED' ELSE 'ACTIVE' END),
LOGIN_LOGIN_ATTEMPTS = (SELECT CASE (#USER_FOUND AND #PASSWORD_CORRECT) WHEN 1 THEN 0 ELSE LOGIN_LOGIN_ATTEMPTS + 1 END),
LOGIN_LAST_LOGIN_DATE = (SELECT CASE (#USER_FOUND AND #PASSWORD_CORRECT) WHEN 1 THEN TransactionDateTime ELSE LOGIN_LAST_LOGIN_DATE END),
LOGIN_LAST_LOGIN_LOCATION = null
WHERE LOGIN_EMAIL = UserEmail;
SELECT
IF(#USER_FOUND AND #PASSWORD_CORRECT, LoginUserID,0) AS USER_ID,
#PASSWORD_CORRECT AS AUTHENTICATED,
#USER_FOUND AS USER_EXISTS,
AccountStatus AS ACCOUNT_STATUS,
IF(#USER_FOUND AND #PASSWORD_CORRECT, 0, LoginAttempts + 1) AS LOGIN_ATTEMPTS,
IF(#USER_FOUND AND #PASSWORD_CORRECT, UserRoles,null) AS USER_ROLES;
END
I need help, I want to ask, I send emails in two SQL tables as a body of the email. However, when the first table has no results, sends a blank email to me, even though the results of the second table exists.
The problem is with #body = #html1
Thank you very much
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[qdatum2]'))
DROP VIEW [dbo].[qdatum2]
GO
-- vytvorenie
CREATE VIEW qdatum2 AS
SELECT(A.Firma) AS FIRMA, A.ID, (A.OBEC) AS OBEC, (A.Ulice) AS Ulica, A.Obec2 as 'Obec dod.', A.Ulice2 AS 'Ulica dod.',
VP.IDS AS REGION,
CAST(SUM(CASE WHEN F.RelTpFak = 2 THEN -F.Kc2 ELSE F.Kc2 END) AS DECIMAL(36,2)) AS OBRAT, MAX(F.DATUM) AS MAXDATUM, MIN(F.DATUM) AS MINDATUM
FROM (StwPh_35760532_2015.dbo.AD as A INNER JOIN StwPh_35760532_2015.dbo.sVPULpol AS VP ON A.RefVPrRegion = VP.ID)
inner JOIN StwPh_35760532_2015.dbo.FA AS F ON A.ID = F.RefAD
WHERE DATEADD(MONTH, 6, F.Datum) > GETDATE()
GROUP BY A.ID, a.Firma, A.Obec, A.Ulice, A.Obec2, A.Ulice2, VP.IDS
union all
SELECT(AD.Firma) AS FIRMA, AD.ID, (AD.OBEC) AS OBEC, (AD.Ulice) AS Ulica, AD.Obec2 as 'Obec dod.', AD.Ulice2 AS 'Ulica dod.',
sVPULpol.IDS AS REGION,
CAST(SUM(CASE WHEN FA.RelTpFak = 2 THEN -FA.Kc2 ELSE FA.Kc2 END) AS DECIMAL(36,2)) AS OBRAT, MAX(FA.DATUM) AS MAXDATUM, MIN(FA.DATUM) AS MINDATUM
FROM (AD INNER JOIN sVPULpol ON AD.RefVPrRegion = sVPULpol.ID) inner JOIN FA ON AD.ID = FA.RefAD
WHERE DATEADD(MONTH, 6, FA.Datum) > GETDATE()
GROUP BY AD.ID, ad.Firma, ad.Obec, ad.Ulice,AD.Obec2,AD.Ulice2, sVPULpol.IDS
go
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[qdatum1]'))
DROP VIEW [dbo].[qdatum1]
GO
-- vytvorenie
CREATE VIEW qdatum1 AS
select (AD.Firma) AS FIRMA, AD.ID, (AD.OBEC) AS OBEC, (AD.Ulice) AS Ulica, AD.Obec2 as 'Obec dod.', AD.Ulice2 AS 'Ulica dod.', qdatum2.REGION,
SUM(qdatum2.OBRAT) as OBRAT, max(qdatum2.MAXDATUM) as MAXDATUM, MIN(qdatum2.MINDATUM) AS MINDATUM
from AD INNER JOIN qdatum2 ON AD.ID = qdatum2.ID
group by ad.id, ad.Firma, ad.Obec, ad.Ulice, ad.Obec2, ad.Ulice2, qdatum2.region
go
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[qdatum]'))
DROP VIEW [dbo].[qdatum]
GO
-- vytvorenie
CREATE VIEW qdatum AS
SELECT qDATUM1.*
FROM qdatum1
WHERE DATEADD(DAY, 30, qdatum1.MAXDATUM) < getdate()
and qdatum1.REGION like '%OR%'
and qdatum1.OBRAT > 50
GO
DECLARE #html varchar(max)
SET #html = '<html>'
+ '<H3><font id="Text" style="color: Green;">PREHLAD AKTIVNYCH ZAKAZNIKOV BEZ ODBERU ZA POSLEDNYCH 30 DNI </H3>'
+ '<table border="1" bordercolor="#3300FF" style="background-color:#DDF8CC" width="70%" cellpadding=3 cellspacing=3>'
+ '<tr><font color="Green"><th>Firma</th><th>Obec</th><th>Ulica</th><th>Obec dod.</th><th>Ulica dod.</th><th>Obrat v € za posledných 6 mesiacov</th><th>Posledna. Faktura</th>
</tr>' +
CAST (( SELECT
td = qdatum.FIRMA, ' ',
td = qdatum.OBEC, ' ',
td = CASE WHEN qdatum.Ulica IS NULL THEN '''' ELSE qdatum.Ulica END, ' ',
td = CASE WHEN qdatum.[Obec dod.] IS NULL THEN '''' ELSE qdatum.[Obec dod.] end , ' ',
td = CASE WHEN qdatum.[Ulica dod.] IS NULL THEN '''' ELSE qdatum.[Ulica dod.] END, ' ',
td = qdatum.OBRAT, ' ',
td = CONVERT(VARCHAR(11),qdatum.MAXDATUM, 106)
from StwPh_35760532_2016.dbo.qdatum
where qdatum.REGION like '%B1OR%'
order by qdatum.MAXDATUM
FOR XML PATH ('tr'),ELEMENTS
) AS VARCHAR(MAX))
+
'<table>'
DECLARE #html1 varchar(max)
SET #html1 = '<html>'
+ '<H3><font id="Text" style="color: Green;">PREHLAD KOMUNIKÁCIE SO ZÁKAZNÍKOM REGION B1OR </H3>'
+ '<table border="1" bordercolor="#3300FF" style="background-color:#DDF8CC" width="70%" cellpadding=3 cellspacing=3>'
+ '<tr><font color="Green"><th>Firma</th><th>Obec</th><th>Ulica</th><th>Obec dod.</th><th>Ulica dod.</th><th>Posledna navsteva</th><th>Posledne volanie</th></tr>' +
CAST( (SELECT
td = AD.Firma , ' ',
td = AD.Obec, ' ',
td = CASE WHEN AD.Ulice IS NULL THEN '''' ELSE AD.Ulice END, ' ',
td = CASE WHEN AD.Obec2 IS NULL THEN '''' ELSE AD.Obec2 END, ' ',
td = CASE WHEN AD.Ulice2 IS NULL THEN '''' ELSE AD.Ulice2 END, ' ',
td = CASE WHEN CONVERT(VARCHAR (11), AD.VPrnavsteva, 106) IS NULL THEN '''' ELSE CONVERT(VARCHAR (11), AD.VPrnavsteva, 106) END, ' ',
td = CASE WHEN CONVERT(VARCHAR(11), AD.VPrvolane, 106) IS NULL THEN '''' ELSE CONVERT(VARCHAR(11), AD.VPrvolane, 106) END
FROM StwPh_35760532_2016.dbo.AD INNER JOIN StwPh_35760532_2016.dbo.sVPULpol ON AD.RefVPrRegion = sVPULpol.ID
WHERE AD.VPrnavsteva < DATEADD(DAY, -30 , GETDATE()) AND AD.VPrvolane < DATEADD(DAY, -30 , GETDATE())
AND AD.RefAD IS NULL
AND sVPULpol.IDS like '%B1OR%'
ORDER BY VPrnavsteva DESC
FOR XML PATH ('tr'),ELEMENTS
) AS VARCHAR(MAX))
+
'</table>'
+ #html
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'LACI_ADMINISTRATOR',
--#recipients = 'emailxx',
#copy_recipients = 'emailxy',
--#blind_copy_recipients = 'emailxxy',
#subject ='B1OR report',
#body = #html1,
#body_format = 'HTML'
Try using this:
DECLARE #html varchar(max)
SET #html = '<html>'
+ '<H3><font id="Text" style="color: Green;">PREHLAD AKTIVNYCH ZAKAZNIKOV BEZ ODBERU ZA POSLEDNYCH 30 DNI </H3>'
+ '<table border="1" bordercolor="#3300FF" style="background-color:#DDF8CC" width="70%" cellpadding=3 cellspacing=3>'
+ '<tr><font color="Green"><th>Firma</th><th>Obec</th><th>Ulica</th><th>Obec dod.</th><th>Ulica dod.</th><th>Obrat v € za posledných 6 mesiacov</th><th>Posledna. Faktura</th>
</tr>' +
ISNULL(CAST (( SELECT
td = qdatum.FIRMA, ' ',
td = qdatum.OBEC, ' ',
td = CASE WHEN qdatum.Ulica IS NULL THEN '''' ELSE qdatum.Ulica END, ' ',
td = CASE WHEN qdatum.[Obec dod.] IS NULL THEN '''' ELSE qdatum.[Obec dod.] end , ' ',
td = CASE WHEN qdatum.[Ulica dod.] IS NULL THEN '''' ELSE qdatum.[Ulica dod.] END, ' ',
td = qdatum.OBRAT, ' ',
td = CONVERT(VARCHAR(11),qdatum.MAXDATUM, 106)
from StwPh_35760532_2016.dbo.qdatum
where qdatum.REGION like '%B1OR%'
order by qdatum.MAXDATUM
FOR XML PATH ('tr'),ELEMENTS
) AS VARCHAR(MAX)), '')
+
'<table>'
DECLARE #html1 varchar(max)
SET #html1 = '<html>'
+ '<H3><font id="Text" style="color: Green;">PREHLAD KOMUNIKÁCIE SO ZÁKAZNÍKOM REGION B1OR </H3>'
+ '<table border="1" bordercolor="#3300FF" style="background-color:#DDF8CC" width="70%" cellpadding=3 cellspacing=3>'
+ '<tr><font color="Green"><th>Firma</th><th>Obec</th><th>Ulica</th><th>Obec dod.</th><th>Ulica dod.</th><th>Posledna navsteva</th><th>Posledne volanie</th></tr>' +
ISNULL(CAST( (SELECT
td = AD.Firma , ' ',
td = AD.Obec, ' ',
td = CASE WHEN AD.Ulice IS NULL THEN '''' ELSE AD.Ulice END, ' ',
td = CASE WHEN AD.Obec2 IS NULL THEN '''' ELSE AD.Obec2 END, ' ',
td = CASE WHEN AD.Ulice2 IS NULL THEN '''' ELSE AD.Ulice2 END, ' ',
td = CASE WHEN CONVERT(VARCHAR (11), AD.VPrnavsteva, 106) IS NULL THEN '''' ELSE CONVERT(VARCHAR (11), AD.VPrnavsteva, 106) END, ' ',
td = CASE WHEN CONVERT(VARCHAR(11), AD.VPrvolane, 106) IS NULL THEN '''' ELSE CONVERT(VARCHAR(11), AD.VPrvolane, 106) END
FROM StwPh_35760532_2016.dbo.AD INNER JOIN StwPh_35760532_2016.dbo.sVPULpol ON AD.RefVPrRegion = sVPULpol.ID
WHERE AD.VPrnavsteva < DATEADD(DAY, -30 , GETDATE()) AND AD.VPrvolane < DATEADD(DAY, -30 , GETDATE())
AND AD.RefAD IS NULL
AND sVPULpol.IDS like '%B1OR%'
ORDER BY VPrnavsteva DESC
FOR XML PATH ('tr'),ELEMENTS
) AS VARCHAR(MAX)),'')
+
'</table>'
+ #html
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'LACI_ADMINISTRATOR',
--#recipients = 'emailxx',
#copy_recipients = 'emailxy',
--#blind_copy_recipients = 'emailxxy',
#subject ='B1OR report',
#body = #html1,
#body_format = 'HTML'
I added ISNULL on your CAST(SELECT) so that your variable will not turn to null if SELECT doesn't return data.
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
I'm using something similar to example C on this MSDN page:
http://msdn.microsoft.com/en-us/library/ms190307.aspx
DECLARE #tableHTML NVARCHAR(MAX) ;
SET #tableHTML =
N'<H1>Work Order Report</H1>' +
N'<table border="1">' +
N'<tr><th>Work Order ID</th><th>Product ID</th>' +
N'<th>Name</th><th>Order Qty</th><th>Due Date</th>' +
N'<th>Expected Revenue</th></tr>' +
CAST ( ( SELECT td = wo.WorkOrderID, '',
td = p.ProductID, '',
td = p.Name, '',
td = wo.OrderQty, '',
td = wo.DueDate, '',
td = (p.ListPrice - p.StandardCost) * wo.OrderQty
FROM AdventureWorks.Production.WorkOrder as wo
JOIN AdventureWorks.Production.Product AS p
ON wo.ProductID = p.ProductID
WHERE DueDate > '2004-04-30'
AND DATEDIFF(dd, '2004-04-30', DueDate) < 2
ORDER BY DueDate ASC,
(p.ListPrice - p.StandardCost) * wo.OrderQty DESC
FOR XML PATH('tr'), TYPE
) AS NVARCHAR(MAX) ) +
N'</table>' ;
EXEC msdb.dbo.sp_send_dbmail #recipients='danw#Adventure-Works.com',
#subject = 'Work Order List',
#body = #tableHTML,
#body_format = 'HTML' ;
I have a column called Rating that is set to 'Good' or 'Bad' according to my own logic.
I would like to make all lines that have a rating of 'Bad' have a red background. I know how to do it in HTML, but not sure how to do it with the "FOR XML" query being demonstrated in this example. Seems like I would have to add an attribute to some TD statements, and not others.
You can not do it directly.A little "Handcrafted" HTML is required. Here is an approach that can be used.
Select good and bad records in separate CTE and append the "td" tags. for bad ones append the Style information as-well.
Then append "tr" tags and combine (UNION) data rows and concatenate them using for xmlpath.
I have removed order by columns for simplicity but you can select them in the CTE and order the results later.
Note: I have tested the output HTML and it works but I am not HTML guy so don't mind if there is any mistake in HTML tags.feel free to correct it.
DECLARE #tableHTML NVARCHAR(MAX)
,#Data NVARCHAR (MAX)=''
SET #tableHTML =
N'<H1>Work Order Report</H1>' +
N'<table border="1">' +
N'<tr><th>Work Order ID</th><th>Product ID</th>' +
N'<th>Name</th><th>Order Qty</th><th>Due Date</th>' +
N'<th>Expected Revenue</th></tr>'
;WITH CTE_Good AS
(
SELECT HTMLRowData= N'<td>'+STR(wo.WorkOrderID)+N'</td>'
+N'<td>'+STR(p.ProductID)+N'</td>'
+N'<td>'+p.Name+N'</td>'
+N'<td>'+STR(wo.OrderQty)+N'</td>'
+N'<td>'+CONVERT(VARCHAR(10),wo.DueDate,101)+N'</td>'
+N'<td>'+STR((p.ListPrice - p.StandardCost) * wo.OrderQty)+N'</td>'
FROM AdventureWorks.Production.WorkOrder as wo
JOIN AdventureWorks.Production.Product AS p
ON wo.ProductID = p.ProductID
WHERE DueDate > '2004-04-30'
AND DATEDIFF(dd, '2004-04-30', DueDate) < 2
--AND Rating = 'Good'
)
,CTE_Bad AS
(
SELECT HTMLRowData= N'<td><p style="color:red">'+STR(wo.WorkOrderID)+N'</p></td>'
+N'<td><p style="color:red">'+STR(p.ProductID)+N'</p></td>'
+N'<td><p style="color:red">'+p.Name+N'</p></td>'
+N'<td><p style="color:red">'+STR(wo.OrderQty)+N'</p></td>'
+N'<td><p style="color:red">'+CONVERT(VARCHAR(10),wo.DueDate,101)+N'</p></td>'
+N'<td><p style="color:red">'+STR((p.ListPrice - p.StandardCost) * wo.OrderQty)+N'</p></td>'
FROM AdventureWorks.Production.WorkOrder as wo
JOIN AdventureWorks.Production.Product AS p
ON wo.ProductID = p.ProductID
WHERE DueDate > '2004-04-30'
AND DATEDIFF(dd, '2004-04-30', DueDate) < 2
--AND Rating = 'Bad'
)
SELECT #Data=(SELECT HTMLRows
FROM (
SELECT N'<tr>'+HTMLRowData+N'</tr>' AS HTMLRows FROM CTE_Good
UNION SELECT N'<tr>'+HTMLRowData+N'</tr>' AS HTMLRows FROM CTE_Bad
) mi
FOR XML PATH(''), TYPE
).value('/', 'NVARCHAR(MAX)')
SET #tableHTML=#tableHTML+#Data+N'</table>'
--SELECT #tableHTML
EXEC msdb.dbo.sp_send_dbmail #recipients='danw#Adventure-Works.com',
#subject = 'Work Order List',
#body = #tableHTML,
#body_format = 'HTML' ;
How can I create a table with x attributes and n rows like?
For example:
x = 4 , and n = 10
att1 att2 att3 att4
----------------------
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
declare #x int = 4, #n int = 10
declare #strg nvarchar(1000) = 'create table myTable ('
declare #i int = 1
while #i<= #x
begin
set #strg = #strg + 'att' + cast(#i as varchar(5))+ ' int default ' + CAST(#i as varchar(5)) + ','
set #i = #i + 1
end
set #strg = SUBSTRING(#strg, 1, LEN(#strg)-1) + ')'
-- this creates your table
exec sp_executesql #strg
-- now lets insert rows
set #i = 0
while #i < #n
begin
INSERT INTO myTable DEFAULT VALUES;
set #i = #i + 1
end
-- lets check
select *
from myTable
Here's a script. You could put this into a stored procedure or just leave it as it is. All you have to do is update the initial col and row values.
DECLARE
#cols INT = 4,
#rows INT = 10,
#tablename VARCHAR(20) = 'TestTable'
DECLARE
#i INT = 1,
#j INT = 1,
#sql NVARCHAR(MAX) = 'create table ' + #tablename + '('
WHILE(#i <= #cols)
BEGIN
SET #sql = #sql + 'att' + CAST(#i AS VARCHAR(10)) + ' VARCHAR(10)'
IF NOT #i = #cols
BEGIN
SET #sql = #sql + ', '
END
SET #i = #i + 1
END
SET #sql = #sql + ')'
EXECUTE sp_executesql #sql
SET #sql = 'INSERT INTO ' + #tablename + ' VALUES'
WHILE(#j <= #rows)
BEGIN
SET #i = 1
SET #sql = #sql + '('
WHILE(#i <= #cols)
BEGIN
SET #sql = #sql + '''' + CAST(#i AS VARCHAR(10)) + ''''
IF NOT #i = #cols
BEGIN
SET #sql = #sql + ', '
END
SET #i = #i + 1
END
IF NOT #j = #rows
BEGIN
SET #sql = #sql + '), '
END
SET #j = #j + 1
END
SET #sql = #sql + ')'
EXECUTE sp_executesql #sql
Hope this helps.