Related
CASE WHEN Col1 = 1 THEN
(CASE WHEN Col2=2 THEN 'a' + ', ' END) +
(CASE WHEN Col3=2 THEN 'b' + ', ' END) +
(CASE WHEN Col4=2 THEN 'c' END)
END as Names
Names can be a,b,c or a,b, or b,
How do I remove the character "," at the end? I cannot use replace or stuff etc functions as "Names" is an alias
original Query:
CASE WHEN ht.bTax=0 then
ISNULL(CASE WHEN (r1.iOccType=2) THEN p1.SFIRSTNAME + ' ' + p1.ULASTNAME END,'') +
ISNULL(CASE WHEN (r2.iOcctType=2) THEN p2.SFIRSTNAME + ' ' + p2.ULASTNAME + ', ' END, '') +
ISNULL(CASE WHEN (r3.iOccType=2) THEN p3.SFIRSTNAME + ' ' + p3.ULASTNAME + ', ' END, '') +
ISNULL(CASE WHEN (r4.iOccType=2) THEN p4.SFIRSTNAME + ' ' + p4.ULASTNAME + ', ' END, '') +
ISNULL(CASE WHEN (r5.iOccType=2) THEN p5.SFIRSTNAME + ' ' + p5.ULASTNAME + ', ' END, '')
End AS Names
My solution would be to add the comma to the end of the 'c' result exactly the same as the others then remove the last two characters from the string after the fact. I think it would be cleaner to put your first statement into a cte then select from it while cleaning up the string then:
with cte as(
Select
CASE WHEN 1 = 1 THEN
(CASE WHEN Col2=2 THEN 'a, ' ELSE '' END) +
(CASE WHEN Col3=2 THEN 'b, ' ELSE '' END) +
(CASE WHEN Col3=2 THEN 'c, ' ELSE '' END)
END as Names
)
select SUBSTRING(Names, 0, Len(Names)) as Names from CTE
Alternatively you can just do it inline but you'll have to repeat your string construction a second time this way.
CASE WHEN Col1 = 1 THEN
SUBSTRING(
(CASE WHEN Col2=2 THEN 'a, ' ELSE '' END) +
(CASE WHEN Col3=2 THEN 'b, ' ELSE '' END) +
(CASE WHEN Col4=2 THEN 'c, ' ELSE '' END)
,0, LEN(
(CASE WHEN Col2=2 THEN 'a, ' ELSE '' END) +
(CASE WHEN Col3=2 THEN 'b, ' ELSE '' END) +
(CASE WHEN Col4=2 THEN 'c, ' ELSE '' END)
))
END as Names
Just to explain what I'm doing here:
SUBSTRING (string, start point, end point) - returns contents of string from start point (0 is beginning) and the end point
LEN (string) - returns the amount of characters in the string
By passing 0 as the start and the LEN() of the string as the last parameter, it will return the full string missing the last character (because the index starts at zero). Usually you would have to put LEN() - 1 but apparently LEN does not count the last empty character.
Hello, I have data that looks like this:
I'm trying to come with the code that will calculate the 'MERGE' column.
Basically, I should check, if CLM_x >0 then take the value from SZ_x and concat with the value in CLM_x.
I'm trying to use case when, however I don't know how to skip merging if CLM_x =0:
CASE WHEN CLM_TBL1 > 0 THEN ('Size ' + SZ_1 + '-Qty '+CLM_1) else ... end ...
Please advise, Thank you!
Yuck. This is a bunch of string arithmetic:
select stuff( ((case when clm1_1 > 0 then concat(', Size ', sz_1, '-Qty ', clm1_1) else '' end) +
(case when clm1_2 > 0 then concat(', Size ', sz_2, '-Qty ', clm1_2) else '' end) +
(case when clm1_3 > 0 then concat(', Size ', sz_3, '-Qty ', clm1_3) else '' end)
), 1, 2, ''
) as merge_column
You just need to string the case statements together.
merge =
case
when CLM_1 > 0 then 'Size ' + SZ_1 + '-Qty '+ CLM_1 + ' '
else ''
end
+
case
when CLM_2 > 0 then 'Size ' + SZ_2 + '-Qty '+ CLM_2 + ' '
else ''
end
+
case
when CLM_3 > 0 then 'Size ' + SZ_3 + '-Qty '+ CLM_3 + ' '
else ''
end
I am working on this stored proc which check to see which BIT fields are true and depending on it assigns a text to it using alias name. I want to be able to combine these alias values (string) and have it comma delimited to I can display it on my SSRS report.
Below is part of my stored proc.
,CASE
WHEN sr.[ReservationAlreadySentAttached] = 1 THEN 'Reservation Already Sent'
END AS ReservationAttached
,CASE
WHEN sr.[HPOfficeAttached] = 1 THEN 'H&P Office'
END AS HPOfficeAttached
WHEN sr.[NotesAttached] = 1 THEN 'Notes'
END AS NotesAttached
,CASE
WHEN sr.[OpPermitAttached] = 1 THEN 'Op Permit'
END AS OpPermitAttached
,CASE
WHEN sr.[TestResultsAttached] = 1 THEN 'Test Results'
END AS TestResultsAttached
,CASE
WHEN sr.[ConsultationReportsAttached] = 1 THEN 'Consultation Reports'
END AS ConsultationReportsAttached
,CASE
WHEN sr.[OtherAttached] = 1 THEN 'Other'
END AS OtherAttached
so lets say in case where only NotesAttached and ReservationAlreadySentAttached were only true ones then I want the end result to come out as Notes, Reservation Already Sent.
How do i concatenate these aliases ?
Another option is to build your string and then just remove the leading comma with STUFF()
Example (abbreviated)
Declare #YourTable table (ReservationAlreadySentAttached bit,HPOfficeAttached bit,NotesAttached bit)
Insert Into #YourTable values
(1,0,1)
Select NewValue = stuff(
case when ReservationAlreadySentAttached = 1 then ', Reservation Already Sent' else '' end
+case when HPOfficeAttached = 1 then ', H&P Office' else '' end
+case when NotesAttached = 1 then ', Notes' else '' end
,1,2,'')
From #YourTable
Returns
NewValue
Reservation Already Sent, Notes
EDIT - Just the Expression
NewValue = stuff(
case when sr.[ReservationAlreadySentAttached] = 1 then ', Reservation Already Sent' else '' end
+case when sr.[HPOfficeAttached] = 1 then ', H&P Office' else '' end
+case when sr.[NotesAttached] = 1 then ', Notes' else '' end
,1,2,'')
Not the prettiest solution...
RIGHT((CASE
WHEN sr.[ReservationAlreadySentAttached] = 1
THEN ',Reservation Already Sent'
END + CASE
WHEN sr.[HPOfficeAttached] = 1
THEN ',H&P Office'
END + CASE
WHEN sr.[NotesAttached] = 1
THEN ',Notes'
END + CASE
WHEN sr.[OpPermitAttached] = 1
THEN ',Op Permit'
END + CASE
WHEN sr.[TestResultsAttached] = 1
THEN ',Test Results'
END + CASE
WHEN sr.[ConsultationReportsAttached] = 1
THEN ',Consultation Reports'
END + CASE
WHEN sr.[OtherAttached] = 1
THEN ',Other'
END)
,LEN(CASE
WHEN sr.[ReservationAlreadySentAttached] = 1
THEN ',Reservation Already Sent'
END + CASE
WHEN sr.[HPOfficeAttached] = 1
THEN ',H&P Office'
END + CASE
WHEN sr.[NotesAttached] = 1
THEN ',Notes'
END + CASE
WHEN sr.[OpPermitAttached] = 1
THEN ',Op Permit'
END + CASE
WHEN sr.[TestResultsAttached] = 1
THEN ',Test Results'
END + CASE
WHEN sr.[ConsultationReportsAttached] = 1
THEN ',Consultation Reports'
END + CASE
WHEN sr.[OtherAttached] = 1
THEN ',Other'
END) - 1 )
Edit: You may have to take into consideration when NONE of them are 1 so you don't get Invalid length parameter passed to the right function.
CASE
WHEN sr.[ReservationAlreadySentAttached] = 1 THEN ', Reservation Already Sent' ELSE ''
END
+ CASE
WHEN sr.[HPOfficeAttached] = 1 THEN ', H&P Office' ELSE ''
END
+ CASE etc...
And wrap this in some function to remove the first comma + space.
Have a 5 columns of address data. I need to concatenate these fields into a single address with spaces in between the values if they exist. If the column has a null value I should skip it and not enter any space.
select
case
when street_number != '' THEN (cast(street_number as int))
end as street_number,
case
when street_ext != '' then
case
when street_ext = 50 then '1/2'
end
end as street_ext,
case
when street_direct ! = '' then street_direct
end as street_direct,
case
when site_street ! = '' then site_street
end as site_street,
case
when site_address ! = '' then site_address
end as site_address
from parcel
what I'd like to do is have a variable and assign it to the value of the first column street_number, then when I move on to the next column, street_ext, if it isn't null I'd like to check to see if the variable is null and if not, append a space and the value...and so on down the road.
I'm rusty as hell and could use a push in the right direction.
Thanks everyone.
Use the "+" to concatenate strings in TSQL:
SELECT CASE
WHEN LEN(p.street_number) > 0 THEN p.street_number + ' '
ELSE ''
END +
CASE
WHEN p.street_ext = 50 THEN '1/2'
WHEN LEN(p.street_ext) > 0 THEN ''
ELSE p.street_ext
END + ' ' +
CASE
WHEN LEN(p.street_direct) > 0 THEN p.street_direct + ' '
ELSE ''
END +
CASE
WHEN LEN(p.site_street) > 0 THEN p.site_street + ' '
ELSE ''
END +
CASE
WHEN LEN(p.site_address) > 0 THEN p.site_address + ' '
ELSE ''
END AS full_address
FROM PARCEL p
The LEN function returns zero if the string value is NULL, or a zero length string.
Nested isnulls could do what you need. Something like:
SELECT
ISNULL(streetnumber + ' ', '')
+ ISNULL(streetext + ' ', '')
etc
relying on the fact that NULL + ' ' = NULL.
Something along the lines of:
select coalesce(street_number+' ','')+
coalesce(case when street_ext=50 then '1/2' else null end+' ','')+
coalesce(street_direct+' ','')+
coalesce(site_street+' ','')+
coalesce(site_address,'')
from parcel
I have assumed your data types are all varchar or similar for simplicity. If you are OK with removing any double spaces, how about:
rtrim(ltrim(replace(isnull(street_number) + ' '
+ isnull(street_ext) + ' '
+ isnull(street_direct) + ' '
+ isnull(site_street) + ' '
+ isnull(site_address), ' ', ' ')))
First I would declare the seperator as a variable, because customers are notorious for changing these.
I would do this as follows:
DECLARE #AddressSeperator NVARCHAR(5) = ' '
...and then for the column declation, I'd use the following:
, CONCAT
(
(CASE WHEN LEN(p.street_number) > 0 THEN p.street_number + #AddressSeperator ELSE '' END)
, (CASE WHEN p.street_ext = 50 THEN '1/2' + #AddressSeperator WHEN LEN(p.street_ext) > 0 THEN p.street_ext + #AddressSeperator ELSE '' END)
, (CASE WHEN LEN(p.street_direct) > 0 THEN p.street_direct + #AddressSeperator ELSE '' END)
, (CASE WHEN LEN(p.site_street) > 0 THEN p.site_street + #AddressSeperator ELSE '' END)
, ISNULL(p.site_address, '')
) AS [full_address]
I have to make a manual calculation of the next run date for a job, can you help me?
to get the next run date for a job you can use then sysschedules and sysjobschedules tables
check the next_run_date and next_runtime columns from the table sysjobschedules
next_run_date int Next date on which
the job is scheduled to run. The date
is formatted YYYYMMDD.
next_run_time int Time at which the
job is scheduled to run. The time is
formatted HHMMSS, and uses a 24-hour
clock.
see this script
Select sched.*,jobsched.* FROM msdb.dbo.sysschedules AS sched
inner Join msdb.dbo.sysjobschedules AS jobsched ON sched.schedule_id = jobsched.schedule_id
or you can use the msdb.dbo.sp_help_jobschedule stored procedure, to get the same info.
UPDATE
if you need calculate manually the next_run_date you must check the sysschedules table and see the freq_interval, freq_subday_type, freq_subday_interval, freq_relative_interval, freq_recurrence_factor, active_start_date, active_start_time columns to determine the formula.
check this link to see an example of use.
Check this one:
SELECT
J.NAME JOB,
DATEADD(SS,(H.RUN_TIME)%100,DATEADD(N,(H.RUN_TIME/100)%100,DATEADD(HH,H.RUN_TIME/10000,CONVERT(DATETIME,CONVERT(VARCHAR(8),H.RUN_DATE),112))))
JOB_STARTED,
DATEADD(SS,((H.RUN_DURATION)%10000)%100,DATEADD(N,((H.RUN_DURATION)%10000)/100,DATEADD(HH,(H.RUN_DURATION)/10000,DATEADD(SS,(H.RUN_TIME)%100,DATEADD(N,(H.RUN_TIME/100)%100,DATEADD(HH,H.RUN_TIME/10000,CONVERT(DATETIME,CONVERT(VARCHAR(8),H.RUN_DATE),112)))))))
JOB_COMPLETED,
CONVERT(VARCHAR(2),(H.RUN_DURATION)/10000) + ':' +
CONVERT(VARCHAR(2),((H.RUN_DURATION)%10000)/100)+ ':' +
CONVERT(VARCHAR(2),((H.RUN_DURATION)%10000)%100) RUN_DURATION,
CASE H.RUN_STATUS
WHEN 0 THEN 'FAILED'
WHEN 1 THEN 'SUCCEEDED'
WHEN 2 THEN 'RETRY'
WHEN 3 THEN 'CANCELED'
WHEN 4 THEN 'IN PROGRESS'
END RUN_STATUS
,CASE S.FREQ_TYPE
WHEN 1 THEN 'ONCE'
WHEN 4 THEN ' DAILY'
WHEN 8 THEN ' WEEKLY'
WHEN 16 THEN ' MONTHLY'
WHEN 32 THEN ' MONTHLY RELATIVE'
WHEN 64 THEN ' WHEN SQL SERVER'
ELSE 'N/A' END [FREQ]
,CASE
WHEN S.NEXT_RUN_DATE > 0 THEN DATEADD(N,(NEXT_RUN_TIME%10000)/100,DATEADD(HH,NEXT_RUN_TIME/10000,CONVERT(DATETIME,CONVERT(VARCHAR(8),NEXT_RUN_DATE),112)))
ELSE CONVERT(DATETIME,CONVERT(VARCHAR(8),'19000101'),112) END NEXT_RUN
FROM
MSDB..SYSJOBHISTORY H,
MSDB..SYSJOBS J,
MSDB..SYSJOBSCHEDULES S,
(
SELECT
MAX(INSTANCE_ID) INSTANCE_ID
,JOB_ID
FROM MSDB..SYSJOBHISTORY GROUP BY JOB_ID
) M
WHERE
H.JOB_ID = J.JOB_ID
AND
J.JOB_ID = S.JOB_ID
AND
H.JOB_ID = M.JOB_ID
AND
H.INSTANCE_ID = M.INSTANCE_ID
-- IF you want to check all job for today then uncomments below
-- AND
-- RUN_DATE = (YEAR(GETDATE())*10000) + (MONTH(GETDATE()) * 100) + DAY(GETDATE())
ORDER BY NEXT_RUN
The short answer is that there's no single formula - it varies by value of freq_type.
The site seems to be down at the moment of writing, but there is an article at http://www.sqlmag.com/Article/ArticleID/99593/sql_server_99593.html which covers how to derive this information. Unfortunately, the site doesn't allow Google to cache its content, so it can't be retrieved until the site comes back up
This looks like a decent alternative source for the kind of query you're trying to write.
here is a very nice script where you can get the next run date.
-- http://www.sqlprofessionals.com/blog/sql-scripts/2014/10/06/insight-into-sql-agent-job-schedules/
SELECT [JobName] = [jobs].[name]
,[Enabled] = CASE [jobs].[enabled] WHEN 1 THEN 'Yes' ELSE 'No' END
,[Scheduled] = CASE [schedule].[enabled] WHEN 1 THEN 'Yes' ELSE 'No' END
,[Next_Run_Date] =
CASE [jobschedule].[next_run_date]
WHEN 0 THEN CONVERT(DATETIME, '1900/1/1')
ELSE CONVERT(DATETIME, CONVERT(CHAR(8), [jobschedule].[next_run_date], 112) + ' ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [jobschedule].[next_run_time]), 6), 5, 0, ':'), 3, 0, ':'))
END
,[Category] = [categories].[name]
,[Owner] = SUSER_SNAME([jobs].[owner_sid])
,[Description] = [jobs].[description]
,[Occurs] =
CASE [schedule].[freq_type]
WHEN 1 THEN 'Once'
WHEN 4 THEN 'Daily'
WHEN 8 THEN 'Weekly'
WHEN 16 THEN 'Monthly'
WHEN 32 THEN 'Monthly relative'
WHEN 64 THEN 'When SQL Server Agent starts'
WHEN 128 THEN 'Start whenever the CPU(s) become idle'
ELSE ''
END
,[Occurs_detail] =
CASE [schedule].[freq_type]
WHEN 1 THEN 'O'
WHEN 4 THEN 'Every ' + CONVERT(VARCHAR, [schedule].[freq_interval]) + ' day(s)'
WHEN 8 THEN 'Every ' + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ' weeks(s) on ' +
LEFT(
CASE WHEN [schedule].[freq_interval] & 1 = 1 THEN 'Sunday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 2 = 2 THEN 'Monday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 4 = 4 THEN 'Tuesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 8 = 8 THEN 'Wednesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 16 = 16 THEN 'Thursday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 32 = 32 THEN 'Friday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 64 = 64 THEN 'Saturday, ' ELSE '' END ,
LEN(
CASE WHEN [schedule].[freq_interval] & 1 = 1 THEN 'Sunday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 2 = 2 THEN 'Monday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 4 = 4 THEN 'Tuesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 8 = 8 THEN 'Wednesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 16 = 16 THEN 'Thursday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 32 = 32 THEN 'Friday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 64 = 64 THEN 'Saturday, ' ELSE '' END
) - 1
)
WHEN 16 THEN 'Day ' + CONVERT(VARCHAR, [schedule].[freq_interval]) + ' of every ' + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ' month(s)'
WHEN 32 THEN 'The ' +
CASE [schedule].[freq_relative_interval]
WHEN 1 THEN 'First'
WHEN 2 THEN 'Second'
WHEN 4 THEN 'Third'
WHEN 8 THEN 'Fourth'
WHEN 16 THEN 'Last'
END +
CASE [schedule].[freq_interval]
WHEN 1 THEN ' Sunday'
WHEN 2 THEN ' Monday'
WHEN 3 THEN ' Tuesday'
WHEN 4 THEN ' Wednesday'
WHEN 5 THEN ' Thursday'
WHEN 6 THEN ' Friday'
WHEN 7 THEN ' Saturday'
WHEN 8 THEN ' Day'
WHEN 9 THEN ' Weekday'
WHEN 10 THEN ' Weekend Day'
END + ' of every ' + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ' month(s)'
ELSE ''
END
,[Frequency] =
CASE [schedule].[freq_subday_type]
WHEN 1 THEN 'Occurs once at ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':')
WHEN 2 THEN 'Occurs every ' +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ' Seconds(s) between ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':') + ' and ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ':'), 3, 0, ':')
WHEN 4 THEN 'Occurs every ' +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ' Minute(s) between ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':') + ' and ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ':'), 3, 0, ':')
WHEN 8 THEN 'Occurs every ' +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ' Hour(s) between ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':') + ' and ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ':'), 3, 0, ':')
ELSE ''
END
,[AvgDurationInSec] = CONVERT(DECIMAL(10, 2), [jobhistory].[AvgDuration])
FROM [msdb].[dbo].[sysjobs] AS [jobs] WITh(NOLOCK)
LEFT OUTER JOIN [msdb].[dbo].[sysjobschedules] AS [jobschedule] WITh(NOLOCK)
ON [jobs].[job_id] = [jobschedule].[job_id]
LEFT OUTER JOIN [msdb].[dbo].[sysschedules] AS [schedule] WITh(NOLOCK)
ON [jobschedule].[schedule_id] = [schedule].[schedule_id]
INNER JOIN [msdb].[dbo].[syscategories] [categories] WITh(NOLOCK)
ON [jobs].[category_id] = [categories].[category_id]
LEFT OUTER JOIN
( SELECT [job_id], [AvgDuration] = (SUM((([run_duration] / 10000 * 3600) +
(([run_duration] % 10000) / 100 * 60) +
([run_duration] % 10000) % 100)) * 1.0) / COUNT([job_id])
FROM [msdb].[dbo].[sysjobhistory] WITh(NOLOCK)
WHERE [step_id] = 0
GROUP BY [job_id]
) AS [jobhistory]
ON [jobhistory].[job_id] = [jobs].[job_id];