简体   繁体   中英

how to convert/calculate nvarchar to int

I'm trying to convert nvarchar(12) to int so i can use it in my code-behind, the data in my column is time related (HH:MM) as below:

00:02
00:55
01:22
05:16

I would like to convert it to be as calculated minutes :

2
55
82
316

I tried to use below sql:

SELECT LTRIM(DATEDIFF(MINUTE, 0, column1)) 
FROM tstable

but it gives below error:

Conversion failed when converting date and/or time from character string

The following works in SQL Server:

select datediff(minute, 0, '05:16')

So this should also work:

select datediff(minute, 0, column1)

This even works with spaces on either side of the string.

Try this..

SELECT 
CAST(SUBSTRING(your_column,1,CHARINDEX(':',your_column,0)-1)AS INT)*60+
CAST(SUBSTRING(your_column,CHARINDEX(':',your_column,0)+1,LEN(your_column)) AS INT) AS T_MIN
FROM your_table

Since the data type is nvarchar, you could you by STRING methods:

DECLARE @HhMm AS NVARCHAR(12) = '05:16';
SELECT LEFT(@HhMm, 2) * 60 + RIGHT(@HhMm, 2) 

Result as 316

Demo with given sample data:

DECLARE @TestTable TABLE (TimeVal NVARCHAR (12));
INSERT INTO @TestTable (TimeVal)  VALUES ('00:02'), ('00:55'), ('01:22'), ('05:16');

SELECT LEFT(TimeVal, 2) * 60 + RIGHT(TimeVal, 2) AS MinutesVal
FROM @TestTable

Output:

MinutesVal
-----------
2
55
82
316
select LEFT(Time1, 2) * 60 + Right(Time1, 2) Minutes from table6

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM