I want to show a specific text in a stored procedure if the date is dec 24'th. How can I check if the current date is dec 24'th and then set a specific text and otherwise the text should be blank.
Are you looking for something like this?
SELECT
CASE WHEN MONTH(GETDATE()) = 12 AND DAY(GETDATE()) = 24
THEN 'Merry Christmas!'
ELSE ''
END
declare #dateString nvarchar(50) = '2018-12-20';
declare #text nvarchar(50);
If Convert(Date, GetDate()) = Convert(Date, dateString)
set #text = "This is it"
if(datepart(MONTH,GETDATE())=12 AND datepart(DAY,GETDATE())=24)
SELECT 'it is dec 24th'
else
SELECT ' '
--- you can use datename() instead of datepart() to get month as text 12>>december
If you are using SQL Server 2012 and above, below is a shorter and efficient script:
SELECT IIF(MONTH(GETDATE()) = 12 AND DAY(GETDATE()) = 24, 'Your Text', '')
You can use the FORMAT() function, available in SQL 2012 and newer:
SELECT CASE WHEN FORMAT(GETDATE(), 'MM-dd') = '12-24'
THEN 'ALMOST XMAS'
ELSE ''
END AS TEXT
Or combined with IIF():
SELECT IIF(FORMAT(GETDATE(), 'MM-dd') = '12-24', 'ALMOST XMAS', '') AS TEXT
Related
I have many records with a string like 'May 2nd 2017'.
What would be the best way to convert to datetime? I was hoping to do it directly in SQL Server...Otherwise I'll just have to loop the records with PHP...
If the month is 3 characters like Aug vs. August
Declare #S varchar(50) = 'May 2nd 2017'
Select try_convert(date,replace(replace(replace(replace(#S,'st',''),'nd',''),'rd',''),'th',''))
If Full month, just one more replace to correct August
Declare #S varchar(50) = 'August 2nd 2017'
Select try_convert(date,replace(replace(replace(replace(replace(#S,'st',''),'nd',''),'rd',''),'th',''),'u ',' '))
You need to think of server language setting when doing that. This would work in older versions too:
DECLARE #v VARCHAR(20) ='May 2nd 2017';
SET LANGUAGE us_english;
SELECT CONVERT(DATETIME,
LEFT(#v, 3)+
REPLACE(REPLACE(REPLACE(REPLACE(
RIGHT(#v, LEN(#v)-3), 'st', ''), 'nd', ''), 'rd', ''), 'th', ''), 9);
I know in SQL Server, a zero-length string ('') is different from null, but is there any way to determine whether it is a zero-length string or null?
The business requirement is:
If user input an index word, let's say IN_DATE, then match the IN_DATE;
If user input nothing for IN_DATE, then match every thing
I tested by using following statements.
DECLARE #IN_DATE VARCHAR(8)
SET #IN_DATE = null
--SET #IN_DATE = ''
SELECT
CONVERT(VARCHAR(8), ISNULL(#IN_DATE, GETDATE()), 112) AS OUT_DATE
Neither null nor zero-length VARCHAR will bring me the expected result. But I tried the following query which works correctly.
SELECT
CONVERT(VARCHAR(8), ISNULL(NULL, GETDATE()), 112) AS OUT_DATE
Anyone can tell me what's the internal logic of these queries? Thanks so much.
DECLARE #PASSED AS VARCHAR(50) = NULL
SELECT
CASE
WHEN ISDATE(#PASSED) = 0 THEN GETDATE()
ELSE CONVERT(DATE, #PASSED)
END AS DATE_OUT
1) If NULL is used for passed then today's date is returned
2) If text '13/13/2014' is passed but not a valid date then again today's date is passed
3) If a valid date '03/13/2014' is passed it is converted into a valid date type
To default to today if the variable is NULL or empty;
SELECT ISNULL(NULLIF(#IN_DATE, ''), GETDATE())
For (2) If user input nothing for IN_DATE, then match every thing
WHERE
(NULLIF(#IN_DATE, '') IS NULL OR SomeField = #IN_DATE)
DECLARE #IN_DATE VARCHAR(8) = ''
SELECT
(CASE #IN_DATE WHEN ''
THEN CONVERT(VARCHAR(100), GETDATE(), 112)
ELSE #IN_DATE END) AS OUT_DATE
I come from a programming background, and i'm having some difficulty wrapping my head around SQL's conditionals.
I'm looking to auto-generate emails when two criteria are met in my sql table.
If the value in column NextTestDate is not null AND today's date is equivalent to the next test date + 30 days THEN generate an email.
SELECT * FROM dbo.datmaintest
if NextTestDate is NOT NULL
AND DATEADD(day,30,DATEDIFF(day, 0, GETDATE())) = DATEADD(DAY, DATEDIFF(day, 0, NextTest), 0) then
BEGIN
use msdb
GO
EXEC sp_send_dbmail #profile_name='ControllerDB',
#recipients='test#test.com',
#subject='ITS ALIVE!',
#body='Time to grab lunch'
END
Think that you are looking for something like this.
IF EXISTS(
select *
FROM dbo.datmaintest
where DATEADD(day, 30, DATEDIFF(day, 0, GETDATE())) = NextTestDate
)
EXEC sp_send_dbmail #profile_name='ControllerDB'
, #recipients = 'test#test.com'
, #subject = 'ITS ALIVE!'
, #body = 'Time to grab lunch'
Something like this should get you started (I'm assuming that in the date logic portion, you meant to type 'NextTestDate' instead of 'NextTest'):
DECLARE #NextTestDate DATETIME
SET #NextTestDate = (SELECT TOP 1 NextTestDate FROM dbo.datmaintest)
--If the value is not null and today is equal to the value of 'next test date' + 30 days:
IF #NextTestDate IS NOT NULL
AND DATEDIFF(DAY, #NextTestDate, GETDATE()) = 30
BEGIN
use msdb
GO
EXEC sp_send_dbmail #profile_name='ControllerDB',
#recipients='test#test.com',
#subject='ITS ALIVE!',
#body='Time to grab lunch'
END
Basically, declare a variable and set it to the value from the database you want to check. Then, perform your check and if it is true, begin the email sending (and close it out with an END)
I have a table which contains 'NULL' values which are of type 'Datetime'. Now i have to convert those into empty string but when when i use convert function
ISNULL( [Accrued Out of Default] ,'' )
here accrued into default is of datetime type, what it does it changes null to '1900-01-01 00:00:00.000' instead of empty
Then i try to convert them into varchar and apply same
ISNULL(CONVERT(varchar(50), [Amort Into Default] ),'')
Now I am able to convert into empty string but now those datetime are converted to string which I needed in datetime
So I try to CAST, CONVERT but non of them works.
CONVERT(Datetime,'ISNULL(CONVERT(varchar(50), [Amort Into Default] ),'')',120)
This gives error.
Is there any possible solution to this.
> **Solution Hi someone answered this to do as.
> ISNULL(CONVERT(varchar(50), [Amort Into Default] ,120),'') and it works I dont know why .
**
CASE and CAST should work:
CASE WHEN mycol IS NULL THEN '' ELSE CONVERT(varchar(50), mycol, 121) END
using an ISNULL is the best way I found of getting round the NULL in dates :
ISNULL(CASE WHEN CONVERT(DATE, YOURDate) = '1900-01-01' THEN '' ELSE CONVERT(CHAR(10), YOURDate, 103) END, '') AS [YOUR Date]
declare #date datetime; set #date = null
--declare #date datetime; set #date = '2015-01-01'
select coalesce( convert( varchar(10), #date, 103 ), '')
I had something similar, and here's (an edited) version of what I ended up using successfully:
ISNULL(CONVERT(VARCHAR(50),[column name goes here],[date style goes here] ),'')
Here's why this works: If you select a date which is NULL, it will show return NULL, though it is really stored as 01/01/1900. This is why an ISNULL on the date field, while you're working with any date data type will not treat this as a NULL, as it is technically not being stored as a NULL.
However, once you convert it to a new datatype, it will convert it as a NULL, and at that point, you're ISNULL will work as you expect it to work.
I hope this works out for you as well!
~Eli
Update, nearly one year later:
I had a similar situation, where I needed the output to be of the date data-type, and my aforementioned solution didn't work (it only works if you need it displayed as a date, not be of the date data type.
If you need it to be of the date data-type, there is a way around it, and this is to nest a REPLACE within an ISNULL, the following worked for me:
Select
ISNULL(
REPLACE(
[DATE COLUMN NAME],
'1900-01-01',
''
),
'') AS [MeaningfulAlias]
This also works:
REPLACE(ISNULL(CONVERT(DATE, #date), ''), '1900-01-01', '') AS 'Your Date Field'
select case when IsNull(CONVERT(DATE, StartDate),'')='' then 'NA' else Convert(varchar(10),StartDate,121) end from table1
Select isnull(date_column_name,cast('1900-01-01' as DATE)) from table name
declare #mydatetime datetime
set #mydatetime = GETDATE() -- comment out for null value
--set #mydatetime = GETDATE()
select
case when #mydatetime IS NULL THEN ''
else convert(varchar(20),#mydatetime,120)
end as converted_date
In this query, I worked out the result came from current date of the day.
You could try the following
select
case when mydatetime IS NULL THEN ''
else convert(varchar(20),#mydatetime,120)
end as converted_date
from sometable
-- Testing it out could do --
declare #mydatetime datetime
set #mydatetime = GETDATE() -- comment out for null value
--set #mydatetime = GETDATE()
select
case when #mydatetime IS NULL THEN ''
else convert(varchar(20),#mydatetime,120)
end as converted_date
Hope this helps!
Try to use the function DECODE
Ex: Decode(MYDATE, NULL, ' ', MYDATE)
If date is NULL then display ' ' (BLANK) else display the date.
With SQL-server 2008 database I have a char(14) data type that I want to convert to a datetime.
Example char(14) values:
20120209102026
20010131120000
The date format is yyyymmdd of some sort.
It seems like the values I posted are not the only format, because I get an "index out of range" error for some of the values. For this I can skip the ones that are not valid dates.
declare #c char(14)
select #c='20120209102026'
Select Cast(Substring(#c,1,8) + ' ' + Substring(#c,9,2)+':'+
Substring(#c,11,2)+':'+ Substring(#c,13,2) as DateTime)
Second Version that ignores out of range numeric values:
Select Cast(
Rtrim(Substring(#c,1,8)
+ Case When len(Substring(#c,9,4))>=4 then +' '+ Substring(#c,9,2) else '' end
+ Case When len(Substring(#c,11,2))=2 then +':'+ Substring(#c,11,2) else '' end
+ Case When len(Substring(#c,13,2))=2 then +':'+ Substring(#c,13,2) else '' end)
as Datetime)
This is ugly but if your format is yyyymmddhhmmss then you can use:
select cast(left(yourDate, 8)+' '+
SUBSTRING(yourDate, 9, 2)+':'+SUBSTRING(yourDate, 11, 2)+':'+RIGHT(yourDate, 2) as datetime)
from yourtable
See SQL Fiddle with Demo
A series of function calls but ends up with the same outcome.
Try like this:
select convert(datetime,STUFF(STUFF(STUFF(STUFF(STUFF('20010131120000',5,0,'/'),8,0,'/'),11,0,' '),14,0,':'),17,0,':'))
Look here for how STUFF works!