How to concatenate integer with string - sql

i'm trying this
CAST(DATEDIFF(month,[patient_date_birth],getdate()) as varchar(10))+ 'month'
but not working !!
any help please
This is my select query
SELECT study_patient_name+' '+study_patient_prenom as Patient,
CASE
WHEN DATEDIFF(month,patient_date_birth,getdate()) > 12 THEN DATEDIFF(year,patient_date_birth,getdate())
ELSE CAST(DATEDIFF(month,patient_date_birth,getdate()) as varchar )+ ' month'
END as Age
from patient

This should work
CAST(DATEDIFF(month,CAST([patient_date_birth] AS DATE),getdate()) as varchar(10))+ ' month'

the error i made is i didn't cast the first part of case CAST(DATEDIFF(year,patient_date_birth,getdate()) as varchar)

You need to cast both elements of the CASE statement to varchar so the result is always varchar regardless of whether 'month' appears in the result:
SELECT
'dave'+' '+'rave' as Patient,
'ENT' as Service,
CASE
WHEN DATEDIFF(month, '2015-02-25', getdate()) > 12
THEN CAST(DATEDIFF(year, '2015-02-25', getdate()) as varchar(10))
ELSE CAST(DATEDIFF(month, '2015-02-25', getdate()) as varchar(10)) + ' month'
END as Age

Related

CONCAT leading 0 in case statement

I found an error in a query I inherited from a previous coworker that I am trying to fix but it's a weird issue I haven't encountered before.. here is a snip of the original query:
CAST(CONCAT(DATEPART(YYYY,getdate()),
(CASE
WHEN DATEPART(WW,getdate()) < 10
THEN CONCAT('0', DATEPART(WW,getdate()))
ELSE DATEPART(WW,getdate())
END)
) AS INT)
When getdate() = 2021-01-08 10:16:41.440 the query results in
20212
Expected result should be
202102
I found the issue relies in in the CASE statement. When I tried to change the THEN clause to
CAST(CONCAT(DATEPART(YYYY,getdate()),
(CASE
WHEN DATEPART(WW,getdate()) < 10
THEN RIGHT('0'+ CONVERT(VARCHAR(2), DATEPART(WW,getdate())),2)
ELSE DATEPART(WW,getdate())
END)
) AS INT)
I still get
20212
But when I run
SELECT RIGHT('0'+ CONVERT(VARCHAR(2), DATEPART(WW,getdate())),2)
I get
02
Can someone explain this? Why does it work outside of the CASE statement, but not within?
case expressions return a single value and that has a single type. If any of the return values are numbers, then the return value is a number, not a string.
To get a string, use datename():
(CASE WHEN DATEPART(WW, getdate()) < 10
THEN CONCAT('0', DATENAME(WW,getdate()))
ELSE DATENAME(WW, getdate())
END)
Or you could simplify your logic:
RIGHT(CONCAT('0', DATENAME(WW, getdate()), 2)
Or simplify everything. For instance, a number might be sufficient:
YEAR(GETDATE()) * 100 + DATEPART(WW, getdate())
Your query has implicit cast to INT:
CAST(CONCAT(DATEPART(YYYY,getdate()),
(CASE
WHEN DATEPART(WW,getdate()) < 10
THEN RIGHT('0'+ CONVERT(VARCHAR(2), DATEPART(WW,getdate())),2)
ELSE CAST(DATEPART(WW,getdate()) AS VARCHAR(2)) -- adding explicit cast here
END)
) AS INT)
I can advice the simple way:
SELECT
CAST(
CONCAT(
DATEPART(YYYY,getdate()),
RIGHT(CONCAT('0000', DATEPART(WW,getdate())), 2)
) AS INT);
You can try T-SQL here

simplify a SQL case statement in a case expression

How would I simplify this case statement in T-SQL? It provides the desired result, but it's very unwieldy and hard to read. I have to use the inner case statement to convert a Julian date (aka 6 digit number) into a regular date format.
Basically i'm doing a datediff( getdate(), case statement). Getdate() just returns the time now (ie. 2/27/2020) and the case statement converts a julian date (ie. 123456) into a normal date (ie, 1/1/2020).
Here's the expect output if the query was ran today on Feb 27.
Select CASE
WHEN Datediff(day, Getdate(), CASE
WHEN a.wadpl = 0
THEN NULL
ELSE Dateadd(d, Substring(Cast(wadpl AS VARCHAR(6)), 4, 3) - 1, CONVERT(DATETIME, CASE
WHEN LEFT(Cast(wadpl AS VARCHAR(6)), 1) = '1'
THEN '20'
ELSE '21'
END + Substring(Cast(wadpl AS VARCHAR(6)), 2, 2) + '-01-01'))
END) < 0
THEN 'Overdue Now'
WHEN Datediff(day, Getdate(), CASE
WHEN a.wadpl = 0
THEN NULL
ELSE Dateadd(d, Substring(Cast(wadpl AS VARCHAR(6)), 4, 3) - 1, CONVERT(DATETIME, CASE
WHEN LEFT(Cast(wadpl AS VARCHAR(6)), 1) = '1'
THEN '20'
ELSE '21'
END + Substring(Cast(wadpl AS VARCHAR(6)), 2, 2) + '-01-01'))
END) <= 30
THEN 'Coming due in 01-30 days'
ELSE 'Not Overdue'
END [Overdue Status]
FROM Table_X
Here is a easy one to understand, assuming a.wadpl is an integer:
SELECT CASE
WHEN DATEDIFF(DAY, GETDATE(), DATEADD(DAY, a.wadpl % 1000, DATEADD(YEAR,a.wadpl / 1000,'1899-12-31'))) <0 THEN 'Overdue now'
WHEN DATEDIFF(DAY, GETDATE(), DATEADD(DAY, a.wadpl % 1000, DATEADD(YEAR,a.wadpl / 1000,'1899-12-31'))) <= 30 THEN 'Coming due in 01-30 days'
ELSE 'Not Overdue'
END [Overdue Status]
FROM Table_X
or you can simplify by using a subquery (or you can use a WITH):
SELECT CASE
WHEN Age <0 THEN 'Overdue now'
WHEN Age <= 30 THEN 'Coming due in 01-30 days'
ELSE 'Not Overdue'
END [Overdue Status]
FROM (
SELECT DATEDIFF(DAY,GETDATE(),
DATEADD(DAY,wadpl%1000,DATEADD(YEAR,wadpl/1000,'1899-12-31'))) Age, *
FROM Table_X) a
This will of course cause you to do this arithmetic for each row, and you can't easily use any indexes. If you were asking about aggregates, then I would suggest doing the opposite, and pre-calculating the dates and use those in your query instead. You might also want to consider putting a persisted computed column on table_x:
ALTER TABLE TABLE_X
ADD wadpl_dt AS
(DATEADD(DAY,wadpl%1000,DATEADD(YEAR,wadpl/1000,'1899-12-31'))) PERSISTED;
Now you can just refer to table_x.wadpl_dt whenever you want the datetime, and your query would become:
SELECT CASE
WHEN Age <0 THEN 'Overdue now'
WHEN Age <= 30 THEN 'Coming due in 01-30 days'
ELSE 'Not Overdue'
END [Overdue Status]
FROM (
SELECT DATEDIFF(DAY,GETDATE(), wadpl_dt) Age, *
FROM Table_X) a
Here is the easy way to convert a date to what you refer to as the julian date:
SELECT (DATEPART(YEAR,GETDATE())-1900) * 1000 + DATEPART(DAYOFYEAR, GETDATE())
And this is how you can use it:
DECLARE #overdue int;
DECLARE #next30 int;
SET #overdue = (SELECT (DATEPART(YEAR,GETDATE())-1900) * 1000 + DATEPART(DAYOFYEAR, GETDATE()));
SET #next30 = (SELECT (DATEPART(YEAR,GETDATE()+30)-1900) * 1000 + DATEPART(DAYOFYEAR, GETDATE()+30));
SELECT CASE
WHEN wadpl < #overdue THEN 'Overdue now'
WHEN wadpl <= #next30 THEN 'Coming due in 01-30 days'
ELSE 'Not Overdue'
END [Overdue Status]
FROM Table_X

T- SQL compare two date column and find month number

I am new in this business. hope you could help me to sort out below problem with CASE Statement. I need to compare two columns where date values are there but the result will be as like as the picture below.
Thank you
Nayeem
Try something like this...
select
first_date
,second_date
,case
when first_date > second_date
then
substring(datename(month,first_date),1,3) + '-' + substring(datename(year,first_date),3,2)
else
substring(datename(month,second_date),1,3) + '-' + substring(datename(year,second_date),3,2)
end as result
from (
select CONVERT(datetime, '2017-08-25') as first_date ,CONVERT(datetime, '2017-02-02') as second_date
union
select CONVERT(datetime, '2018-01-25') as first_date ,CONVERT(datetime, '2018-12-04') as second_date
union
select CONVERT(datetime, '2019-11-14') as first_date ,CONVERT(datetime, '2019-11-14') as second_date
) x;
;
Assuming your date columns are indeed dates, you seem to be looking for:
select format(coalesce(start_date_1, start_date_2), 'MMM-yy')
from t;

How to convert Date in sql 05/04/207 as 4MAY2017

I am using
CONVERT(nvarchar, Date, 106)
it gives 04MAY2017
but i need 4MAY2017 FOR 04/05/2017
and 11MAY2017 FOR 11/05/2017
If CONVERT(nvarchar, Date, 106) gives 04MAY2017 and you if you want to remove the first character if it is 0 then you can use a CASE expression.
Query
SELECT CASE WHEN LEFT(CONVERT(nvarchar, Date, 106), 1) = '0'
THEN RIGHT(CONVERT(nvarchar, Date, 106), LEN(CONVERT(nvarchar, Date, 106)) - 1)
ELSE CONVERT(nvarchar, Date, 106) END
FROM your_table_name;
You could check when day-in-month < 10 then remove first character.
SELECT REPLACE(CASE
WHEN datepart(day,dateColumn) < 10
THEN STUFF(convert(nvarchar(20), dateColumn, 106), 1,1,'')
ELSE convert(nvarchar(20), dateColumn, 106)
END, ' ', '') AS dateText
FROM yourTable

Get Hours and Minutes (HH:MM) from date

I want to get only hh:mm from date.
How I can get this?
I have tried this :
CONVERT(VARCHAR(8), getdate(), 108)
Just use the first 5 characters...?
SELECT CONVERT(VARCHAR(5),getdate(),108)
You can easily use Format() function instead of all the casting for sql 2012 and above only
SELECT FORMAT(GETDATE(),'hh:mm')
This is by far the best way to do the required conversion.
Another method using DATEPART built-in function:
SELECT cast(DATEPART(hour, GETDATE()) as varchar) + ':' + cast(DATEPART(minute, GETDATE()) as varchar)
If you want to display 24 hours format use:
SELECT FORMAT(GETDATE(),'HH:mm')
and to display 12 hours format use:
SELECT FORMAT(GETDATE(),'hh:mm')
Following code shows current hour and minutes in 'Hour:Minutes' column for us.
SELECT CONVERT(VARCHAR(5), GETDATE(), 108) +
(CASE WHEN DATEPART(HOUR, GETDATE()) > 12 THEN ' PM'
ELSE ' AM'
END) 'Hour:Minutes'
or
SELECT Format(GETDATE(), 'hh:mm') +
(CASE WHEN DATEPART(HOUR, GETDATE()) > 12 THEN ' PM'
ELSE ' AM'
END) 'Hour:Minutes'
The following works on 2008R2+ to produce 'HH:MM':
select
case
when len(replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')) = 4
then '0'+ replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')
else replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','') end as [Time]
You can cast datetime to time
select CAST(GETDATE() as time)
If you want a hh:mm format
select cast(CAST(GETDATE() as time) as varchar(5))
Here is syntax for showing hours and minutes for a field coming out of a SELECT statement. In this example, the SQL field is named "UpdatedOnAt" and is a DateTime. Tested with MS SQL 2014.
SELECT Format(UpdatedOnAt ,'hh:mm') as UpdatedOnAt from MyTable
I like the format that shows the day of the week as a 3-letter abbreviation, and includes the seconds:
SELECT Format(UpdatedOnAt ,'ddd hh:mm:ss') as UpdatedOnAt from MyTable
The "as UpdatedOnAt" suffix is optional. It gives you a column heading equal tot he field you were selecting to begin with.
TO_CHAR(SYSDATE, 'HH')
I used this to get the current hour in apex PL/SQL