how to convert nvarchar(50) to datetime in sqlserver 2008 - sql

hi i wrote this query in SqlServer 2008
but some thing goes wrong
select * from News_Table
where (DATEDIFF( DAY ,convert(datetime, NewsDate) , convert(datetime,#Todaydate )) <= #Count)
that #NewsDate and #Todaydate are two nvarchar parameters that are saved like this 2014/11/16
running this query give me an error:
Conversion failed when converting date and/or time from character string

Try adding the correct style parameter to your convert function (see MSDN: link )
ie CONVERT(DATETIME, NewsDate, 111) (111 is the style for YYYY/MM/DD)
Then you get:
SELECT *
FROM News_Table
WHERE (DATEDIFF( DAY ,
CONVERT(DATETIME, NewsDate, 111) ,
CONVERT(DATETIME,#Todaydate, 111)
) <= #Count)

use Convert(datetime, #yourvalue, 111)
select * from News_Table
where (DATEDIFF( DAY ,convert(datetime, #NewsDate, 111) , convert(datetime,#Todaydate, 111 )) <= #Count)
http://www.sqlusa.com/bestpractices/datetimeconversion/

To know more click here
SELECT convert(datetime, '2014/11/16', 111) as datetime
OP
So your query would be like this
Select * from News_Table
where (DATEDIFF( DAY ,convert(datetime, '2014/11/16', 111) , convert(datetime,#Todaydate,111 )) <= #Count)

Try like this
SELECT *
FROM News_Table
WHERE (DATEDIFF(DAY,CAST(NewsDate AS Datetime),CAST(#Todaydate AS Datetime)) <= #Count)

You will need to do something like this to convert that string into DATETIME datatype
DECLARE #Date NVARCHAR(20) = '2013/11/16'
SELECT CAST((LEFT(#Date, 4) + SUBSTRING(#Date, 6 ,2) + RIGHT(#Date, 2)) AS DATETIME)
for your query
select * from News_Table
where (DATEDIFF( DAY , CAST((LEFT(NewsDate, 4) + SUBSTRING(NewsDate, 6 ,2) + RIGHT(NewsDate, 2)) AS DATETIME)
, CAST((LEFT(#Todaydate, 4) + SUBSTRING(#Todaydate, 6 ,2) + RIGHT(#Todaydate, 2)) AS DATETIME)
) <= #Count)
Note
If variable #Todaydate is actually storing today's date then why not use simply GETDATE() function.

Related

Change date format dd/mm/yyyy to yyyy-mm-dd

am working in SQL Server 2008, while merging I got error like
conversion failed when converting datetime from character string
select *
from table_name
where cast(f_datetime as date) <=
cast(cast(datepart(year,cast(convert(varchar(250),#Year,103) as date) )as varchar(250))+ '-'+ cast(datepart(MM,cast(convert(varchar(10),#month,103) as varchar(50))+'-01' as date)
I cannot speak to the cast() on f_datetime. But for the rest, you can do:
where cast(f_datetime as date) <= convert(date, convert(varchar(250), #year * 10000 + #month * 100 + 1))
This simplifies the calculation, and prevents things like #year from being treated as a date due to the convert() function.
I assume your f_datetime field format is "dd/mm/yyyy". If yes you can easily convert this field instead of trying to merge and convert #year and #month fields. check this query :
SELECT *
FROM table_name
WHERE CONVERT(DATE,f_datetime,103)<= CAST(CONVERT(VARCHAR, #year) + '-' + CONVERT(VARCHAR, #month) + '-' + '01' AS DATE)

Need hour min and sec in a query

I am calculating the time difference between 2 times, I want to print the hour min and sec. Can anyone please tell me how to do it.
My query
SELECT
CONVERT(VARCHAR(8), DATEADD(ms, DATEDIFF(ms, CONVERT(VARCHAR(8), GETDATE(), 114), CONVERT(VARCHAR(8), VCTime, 114)), 0), 114) AS TImeDifference
FROM
Test
Output:
TimeDifference
---------------
10:51:37
20:51:37
21:51:37
22:21:37
08:51:37
00:51:37
Expected Output
TimeDifference
---------------
10h:51m:37s
20h:51m:37s
21h:51m:37s
22h:21m:37s
08h:51m:37s
00h:51m:37s
One way is to use sub query and concatenation operator + for 2008 with DATEPART function as below:
SELECT (
CAST(DATEPART(HOUR,(TImeDifference)) AS VARCHAR) + 'h:' +
CAST(DATEPART(MINUTE,(TImeDifference)) AS VARCHAR) + 'm:' +
CAST(DATEPART(SECOND,(TImeDifference)) AS VARCHAR) + 's')
FROM(
SELECT
CONVERT(varchar(8), DATEADD(ms, DATEDIFF(ms, convert(varchar(8),getdate(),114),
convert(varchar(8),VCTime,114)), 0), 114) as TImeDifference
FROM test
) t
Yes I realized concat is introduced in 2012 so we can use + instead
you can follow below way
DECLARE #x int,
#dt1 smalldatetime = '2018-08-17 03:24:16',
#dt2 smalldatetime = getdate()
SET #x = datediff (s, #dt1, #dt2)
SELECT convert(varchar, #x / (60 * 60 * 24)) + ':'
+ convert(varchar, dateadd(s, #x, convert(datetime2, '0001-01-01')), 108)
this will return 1:05:57:00
Try this:
select cast(date_diff / 3600 as varchar(4)) + 'h:' +
cast((date_diff % 3600) / 60 as varchar(4)) + 'm:' +
cast(date_diff % 60 as varchar(4)) + 's'
from (
select datediff(second, getdate(), VCTime) date_diff from my_table
) a
First, you should not be converting to strings to get the difference. I think this should be fine:
SELECT CONVERT(VARCHAR(8),
DATEDIFF(ms, CAST(GETDATE() as TIME), CAST(VCTime as TIME)),
114
) as TImeDifference
FROM Test;
Then you want to add "h", "m", and "s". You can use the STUFF() function. But let me do this using APPLY so the code doesn't look quite so messy:
SELECT ( STUFF(STUFF(TimeDifference_str, 6, 0, 'm'), 3, 0, 'h') + 's' ) as TimeDifference_hms
FROM test t CROSS APPLY
(VALUES (CONVERT(VARCHAR(8),
DATEDIFF(ms, CAST(GETDATE() as TIME), CAST(VCTime as TIME)),
114
)
)
) v(TimeDifference_str)

Sql returning date time without seconds and milliseconds

my this code returns date time but with seconds milliseconds , i don't want milliseconds and seconds. I tried but not working, help. In this format.
Output:
Code:
Set #DateFrom = Convert(date,(Select min(ReceivedMessages.ReceivedDateTime) from ReceivedMessages))
Set #DateTo = Convert(date,(Select max(ReceivedMessages.ReceivedDateTime) from ReceivedMessages))
SELECT [ID]
,LEFT(REPLACE(convert(varchar, ReceivedMessages.ReceivedDateTime, 113), ' ','/'), 11) + ' ' +
RIGHT(REPLACE(convert(varchar, ReceivedMessages.ReceivedDateTime, 113), ' ','/'), 12)
as RecievingDate
,[FromMobileNo]
,[Message],
[IsComplaint]
FROM [CmsSMSDb].[dbo].[ReceivedMessages]
where Convert(date,ReceivedDateTime)>= #DateFrom AND Convert(date,ReceivedDateTime)<= #DateTo
AND IsComplaint = 2
Try this, but replace GETDATE() with your time
SELECT CONVERT(VARCHAR(16), GETDATE(), 121)
declare #dtime datetime;
set #dtime = getdate();
select REPLACE(CONVERT(varchar(11), #dtime, 113), ' ', '/')
+ RIGHT(CONVERT(varchar(17), #dtime, 113), 6)
You can round datetime to the nearest minute like this:
DECLARE #CaptureDate datetime
SELECT #CaptureDate = DATEADD(minute, DATEDIFF(minute, 0, DATEADD(second, 30 - DATEPART(second, GETDATE() + '00:00:30.000'), GETDATE())), 0)
SELECT CONVERT(VARCHAR(16), #CaptureDate, 120)
Change GETDATE() to your date fields as applicable.

Select * from table where date selected is between

i trying to build the following query to select * from table where the minDate is 03-02-2014 and the maxDate is 01-03-2014
but something i missing.
hope that someone can help me with this.
SELECT * From table Where
SUBSTRING(mydate, 1, 10) >= REPLACE('03-02-2014','-','/') AND
SUBSTRING(mydate, 1, 10) <= REPLACE('01-03-2014','-','/')
Note:
My Date column is of type varchar with a value like this --> 03/02/2014 18:13:16
im working in sql server management studio (t-sql)
From your comments, it seems that the mydate column of your table is in the British format.
Read this article about date conversion in SQL SERVER to understand more about date conversions.
Also updated my answer with the date conversions for this format.
Try something like
SELECT * FROM table
WHERE CONVERT(DATE, SUBSTRING(mydate, 1, 10), 103) >= CONVERT(DATE, '03/02/2014', 103)
AND CONVERT(DATE, SUBSTRING(mydate, 1, 10), 103) <= CONVERT(DATE, '01/03/2014', 103)
you can do something like:
Select * From Table
Where CONVERT( Datetime, mydate ,110 ) between CONVERT( Datetime, #min ,110 ) and between CONVERT( Datetime, #max ,110 )
I don't have SSMS available right now, but for a quick try you might try this
SELECT * From table Where
CAST( SUBSTRING(mydate, 1, 10) as date) BETWEEN CAST( SUBSTRING('START DATE', 1, 10) as date)
AND CAST( SUBSTRING('END DATE', 1, 10) as date)

How to print GETDATE() in SQL Server with milliseconds in time?

I want to print GETDATE() in SQL Server 2008, I need the time with milliseconds (this is for debugging purpose - to find sp's execution time )
I find this Difference
SELECT GETDATE() returns 2011-03-15 18:43:44.100
print GETDATE() returns Mar 15 2011 6:44PM
I think SQL Server automatically typecast in print functionality.
I need to print the date like this 2011-03-15 18:43:44.100
Thanks for your help.
First, you should probably use SYSDATETIME() if you're looking for more precision.
To format your data with milliseconds, try CONVERT(varchar, SYSDATETIME(), 121).
For other formats, check out the MSDN page on CAST and CONVERT.
SELECT CONVERT( VARCHAR(24), GETDATE(), 113)
UPDATE
PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))
If your SQL Server version supports the function FORMAT you could do it like this:
select format(getdate(), 'yyyy-MM-dd HH:mm:ss.fff')
these 2 are the same:
Print CAST(GETDATE() as Datetime2 (3) )
PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))
UPDATE:
better than datetime is datetime2(3)
declare #dt datetime2(3)=sysdatetime()
print #dt
Print CAST(sysdatetime() as Datetime2(3) )
print sysdatetime()
This is equivalent to new Date().getTime() in JavaScript :
Use the below statement to get the time in seconds.
SELECT cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)
Use the below statement to get the time in milliseconds.
SELECT cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint) * 1000
Try Following
DECLARE #formatted_datetime char(23)
SET #formatted_datetime = CONVERT(char(23), GETDATE(), 121)
print #formatted_datetime
Create a function with return format yyyy-mm-hh hh:mi:ss.sss
create function fn_retornaFecha (#i_fecha datetime)
returns varchar(23)
as
begin
declare
#w_fecha varchar(23),
#w_anio varchar(4),
#w_mes varchar(2),
#w_dia varchar(2),
#w_hh varchar(2),
#w_nn varchar(2),
#w_ss varchar(2),
#w_sss varchar(3)
select #w_fecha = null
if ltrim(rtrim(#i_fecha)) is not null
begin
select
#w_anio = replicate('0',4-char_length( convert(varchar(4), year(#i_fecha)) )) + convert(varchar(4), year(#i_fecha)),
#w_mes = replicate('0',2-char_length( convert(varchar(2),month(#i_fecha)) )) + convert(varchar(2),month(#i_fecha)),
#w_dia = replicate('0',2-char_length( convert(varchar(2), day(#i_fecha)) )) + convert(varchar(2), day(#i_fecha)) ,
#w_hh = replicate('0',2-char_length( convert(varchar(2),datepart( hh, #i_fecha ) ) )) + convert(varchar(2),datepart( hh, #i_fecha ) ),
#w_nn = replicate('0',2-char_length( convert(varchar(2),datepart( mi, #i_fecha ) ) )) + convert(varchar(2),datepart( mi, #i_fecha ) ),
#w_ss = replicate('0',2-char_length( convert(varchar(2),datepart( ss, #i_fecha ) ) )) + convert(varchar(2),datepart( ss, #i_fecha ) ),
#w_sss = convert(varchar(3),datepart( ms, #i_fecha ) ) + replicate('0',3-DATALENGTH( convert(varchar(3),datepart( ms, #i_fecha ) ) ))
select #w_fecha = #w_anio + '-' + #w_mes + '-' + #w_dia + ' ' + #w_hh + ':' + #w_nn + ':' + #w_ss + '.' + #w_sss
end
return #w_fecha
end
go
Example
select fn_retornaFecha(getdate())
and the result is: 2016-12-21 10:12:50.123