January 26, 2014 at 11:09 pm
Hi Experts,
please help me in writing a SQL Function as below
the input parameter for function should be datetime of sql datetimeformat
and out put should be a string = yyyymmdd1 or yyyymmdd2
the last character 1 or 2 based on below condition
if time is between 6AM and 5.59PM then 1
if 6PM to 5.59AM then 2
please help me with such function am running out of time
thank you.
Kishore
January 26, 2014 at 11:44 pm
USE Master
GO
DECLARE @dt DATETIME
SELECT @dt = '2014/01/27 01:00 PM'
select REPLACE(CONVERT(VARCHAR(10),@dt,111),'/','')+CASE WHEN DATEPART(HH,@dt) >= 6 AND DATEPART(HH,@dt) < 18 THEN '1' ELSE '2' END
SELECT @dt = '2014/01/27 01:00 AM'
select REPLACE(CONVERT(VARCHAR(10),@dt,111),'/','')+CASE WHEN DATEPART(HH,@dt) >= 6 AND DATEPART(HH,@dt) < 18 THEN '1' ELSE '2' END
Regards,
Mitesh OSwal
+918698619998
January 27, 2014 at 2:06 am
;WITH SampleData AS (
SELECT MyDate = CAST('2014-01-27 05:59:59.997' AS DATETIME) UNION ALL
SELECT '2014-01-27 06:00:00.000' UNION ALL
SELECT '2014-01-27 06:00:00.003' UNION ALL
SELECT '2014-01-27 17:59:59.994' UNION ALL
SELECT '2014-01-27 17:59:59.997' UNION ALL
SELECT '2014-01-27 18:00:00.000')
SELECT
MyDate,
CONVERT(CHAR(8),MyDate, 112) + CASE WHEN DATEPART(HOUR,MyDate) >= 6 AND DATEPART(HOUR,MyDate) < 18 THEN '1' ELSE '2' END
FROM SampleData
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
January 27, 2014 at 2:24 am
It Worked
Thanks a ton Mitesh
January 27, 2014 at 2:25 am
Thank you for the reply chris.:-)
January 27, 2014 at 7:44 am
--EDIT--
It is Monday morning and I misread this post entirely. Need more coffee.
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
January 28, 2014 at 3:55 pm
Greetings!
Would using date type 112 not remove the need to replace the "/" characters in the date string?
This would reduce the date string portion from
REPLACE(CONVERT(VARCHAR(10),@dt,111),'/','')
to
CONVERT(VARCHAR(8),@dt,112)
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply