SQL Server: How to concatenate string constant with date? - sql

select packageid,status+' Date : '+UpdatedOn from [Shipment_Package]
The below error is appeared when executing the above code in sql server. The type of UpdatedOn is DateTime and status is a varchar. We wanted to concatenate the status, Date and UpdatedOn.
error:
Conversion failed when converting date and/or time from character
string.

You need to convert UpdatedOn to varchar something like this:
select packageid, status + ' Date : ' + CAST(UpdatedOn AS VARCHAR(10))
from [Shipment_Package];
You might also need to use CONVERT if you want to format the datetime in a specific format.

To achive what you need, you would need to CAST the Date?
Example would be;
Your current, incorrect code:
select packageid,status+' Date : '+UpdatedOn from [Shipment_Package]
Suggested solution:
select packageid,status + ' Date : ' + CAST(UpdatedOn AS VARCHAR(20))
from [Shipment_Package]
MSDN article for CAST / CONVERT
Hope this helps.

To account for null values, try this:
select packageid,
'Status: ' + isnull(status, '(null)') + ', Date : '
+ case when UpdatedOn is null then '(null)' else convert(varchar(20), UpdatedOn, 104) end as status_text
from [Shipment_Package]

Convert Datetime column into varchar for sql Server you can use below code
select packageid,status+' Date : '+CONVERT(VARCHAR,UpdatedOn,120) from [Shipment_Package]
120 code will convert your date into this format : 2020-06-12 15:09:00
other format you can use from this link

Related

Convert data and time into a numeric number in sql server

I have a data & time format column which I would like to convert to the following format in Microsoft SQL Server: yyyymmddhhmmss00000
So for example if I have 2021-02-04 11:49:50 this will be converted to 2021020411495000000.
Any one knows how to do it please?
You can use the FORMAT function:
SELECT FORMAT(myDate, 'yyyyMMddHHmmss00000')
By converting the date to NVARCHAR once with format 112 and once with format 8 you can extract the numeric date and the time without milliseconds. After removing : from the time you can concat these two strings and convert them to bigint. Following an example:
DECLARE #d DATETIME = GETDATE()
SELECT CAST(CONVERT(NVARCHAR(8), #d, 112) + REPLACE(CONVERT(NVARCHAR(8), #d, 8), ':', '') + '00000' AS BIGINT)

Converting date to YYYYMMDD format in SQL Server 2016 from T format

I have a date column in a SQL table where the values are stored in the below format.
2020-04-07T02:41:49
I need to get the date in YYYYMMDD format, like this: 20200407.
I tried using the below statements but it throws an error on conversion.
SELECT
CONVERT(DATETIME, SUBSTRING(CAST('2020-04-07T02:41:49' AS varchar), 1, 8))
SELECT
LEFT(4, CAST('2020-04-05T08:05:47' AS nvarchar))
Error:
Conversion failed when converting date and/or time from character string
Could someone please help?
Thanks.
You can use try_convert(date,...)
Example
Select WithFormat = format(try_convert(date,'2020-04-07T02:41:49'),'yyyyMMdd')
,OrNot = convert(varchar(10),try_convert(date,'2020-04-07T02:41:49'),112)
,OrString = replace(left('2020-04-07T02:41:49',10),'-','')
Returns
WithFormat OrNot OrString
20200407 20200407 20200407

Convert nvarchar date (DD/MM/YYYY) to Date Period (YYYY_MM)

I am trying to convert this into a period format, so e.g. 2018_05 (YYYY_MM). currently the data is in DD/MM/YYYY format.
I tried a cast code but it returns me YYYY_DD.
SELECT
CASE WHEN RESERVED_FIELD_4 IS NULL THEN NULL
ELSE cast(year(RESERVED_FIELD_4) as Nvarchar (4))
+'_'+right('00'+cast(month(RESERVED_FIELD_4) as Nvarchar (2)),2)
END AS [DATAFEED_PERIOD]
I expect/want to see YYYY_MM.
Assuming RESERVED_FIELD_4 is a string type (char/nchar/varchar/nvarchar) the simplest solution would be to use substring:
CASE
WHEN RESERVED_FIELD_4 IS NULL THEN NULL
ELSE SUBSTRING(RESERVED_FIELD_4, 7, 4) + '_'+ SUBSTRING(RESERVED_FIELD_4, 4, 2)
END AS [DATAFEED_PERIOD]
If it's a date/datetime/datetime2 data type, the simplest solution would be to use format:
FORMAT(RESERVED_FIELD_4, 'yyyy_MM')
But for better performance you can use convert and stuff:
SELECT STUFF(CONVERT(char(6), RESERVED_FIELD_4, 112), 5, 0, '_')
In case your format is actually d/m/y the simplest option is to convert to date and than back to string:
SELECT STUFF(CONVERT(char(6), CONVERT(Date, RESERVED_FIELD_4, 103), 112), 5, 0, '_')
This is the common problem of storing a date with a VARCHAR column. You are guessing that the stored pattern is DD/MM/YYYY but the SQL engine doesn't know that and is currently assuming the MM/DD/YYYY pattern.
Please check these results:
-- MM/DD/YYYY
SELECT
DAY ('05/01/2019'), -- 1
MONTH('05/01/2019') -- 5
-- DD/MM/YYYY
SELECT
DAY ('25/05/2019'), -- Conversion failed when converting date and/or time from character string
MONTH('25/05/2019') -- Conversion failed when converting date and/or time from character string.
To display what you want correctly use string functions:
SELECT
RIGHT(RESERVED_FIELD_4, 4) + '_' + SUBSTRING(RESERVED_FIELD_4, 4, 2)
But you should actually fix the values on your VARCHAR column, cast them to DATE and store the values as DATE.
ALTER TABLE YourTable ADD ReservedField4Date DATE
UPDATE YourTable SET
ReservedField4Date = CONVERT(DATE,
RIGHT(RESERVED_FIELD_4, 4) -- Year
+ '-' + SUBSTRING(RESERVED_FIELD_4, 4, 2) -- Month
+ '-' + LEFT(RESERVED_FIELD_4, 2)) -- Day
ALTER TABLE YourTable DROP COLUMN RESERVED_FIELD_4
EXEC sp_rename 'SchemaName.YourTable.ReservedField4Date', 'RESERVED_FIELD_4', 'COLUMN'
Beware that changing the column type might affect other queries that assume this is a VARCHAR column.
If your data is in DD/MM/YYYY format, then it is being stored as a string. Hence, string functions come to mind:
select right(RESERVED_FIELD_4) + '_' + substrint(RESERVED_FIELD_4, 4, 2)
In SQL-SERVER you can use 'format'
format(dy,#your_date) as day_of_year
month(#your_date) as month
Try this:
Select concat(month(#your_date),'_'year(#your_date)) as your_period
this is a reference
Why not just do conversations ? :
SELECT REPLACE(CONVERT(VARCHAR(7), CONVERT(date, RESERVED_FIELD_4, 101), 102), '.', '_')
This assumes RESERVED_FIELD_4 is date type.

Output year and month with a string

Trying to output something like:
2016,11
Using this:
SELECT
CONVERT(VARCHAR(20),YEAR(GETDATE()) + ',' + MONTH(GETDATE())) AS YearMonth
Am I missing something in convert? Because I am getting this error:
Conversion failed when converting the varchar value ',' to data type
int.
Thanks
Try this.
SELECT
CONVERT(VARCHAR(20),YEAR(GETDATE())) + ',' + CONVERT(VARCHAR(20), MONTH(GETDATE())) AS YearMonth
You might use CONVERT with 112 to reach a string without delimiters ("20161110"). Converting this to VARCHAR(*6*) will implicitly cut the day. One (in most cases positiv) side-effect: You will get a low month zero padded (e.g. 2016,04). Then I use STUFF to insert the ,:
SELECT STUFF(CONVERT(VARCHAR(6),GETDATE(),112),5,0,',')
If you do not like the zero padded month, you could replace the 0 in STUFF like this:
DECLARE #d DATETIME={d'2016-04-05'};
SELECT STUFF(CONVERT(VARCHAR(6),#d,112),5,CASE WHEN MONTH(#d)<10 THEN 1 ELSE 0 END,',')
You are missing converting the output of MONTH() to a string. Here is one method:
select datename(year, getdate()) + ',' + cast(month(getdate()) as varchar(255)) as YearMonth
datename() is convenient because it returns a string. Unfortunately, for month it returns the name of the month, rather than the number.
You could also do:
select replace(convert(varchar(7), getdate(), 120), '-', ',')
Or use format() in SQL Server 2012+:
select format(getdate(), 'yyyy,MM')

Convert a string ddmmyyyyhhmi into yyyy-mm-dd in SQL server

how can I convert a string ddmmyyyyhhmi into yyyy-mm-dd?
A string 210420161701 (a varchar) into 2016-04-21 (a datetime data type).
I tried a combination of sub-string, cast, convert but can't seem to make it work.
Please kindly help thanks.
The first 2 lines are just setting up the variable, but the following works (as long as the format is always the same). You may also need to make sure the date format of your SQL installation is correct (SET DATEFORMAT). You can also change the datatype from date to datetime if required.
DECLARE #Date Varchar(100) = '210420161701'
DECLARE #DateVariable date
SELECT #DateVariable = SUBSTRING(#date,5,4) + '-' + SUBSTRING(#date,3,2) + '-' + SUBSTRING(#date,1,2)
SELECT #DateVariable
select
SUBSTRING(convert(varchar(10),'210420161701',103),5,4)+ '-'+
SUBSTRING(convert(varchar(10),'210420161701',103),3,2)+'-'+
SUBSTRING(convert(varchar(10),'210420161701',103),1,2)