Link to home
Start Free TrialLog in
Avatar of moe57
moe57

asked on

how to convert nvarchar to time in sql server

I have column called Shift_End in my table but the data type is nvarchar.  All the values for this column are military format but nvarchar.  For example like this:
Shift_End
1500
1600
1730
1800
1830
So i want to pull all records where Shift_End > current datetime.  If shift_end is 1600, then i want to see all records after 1600.
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

>I have column called Shift_End in my table but the data type is nvarchar
Two design mistakes on somebody's part:  Storing time data as an nvarchar, and storing time data separate from the date.  If this is to keep track of shifts, you'll need the date and time together to track hours where the shift crosses over midnight.

Either way, try this..
CREATE TABLE #time (Shift_End nvarchar(10)) 

INSERT INTO #time (Shift_End)
VALUES ('1500'), ('1600'), ('1730'), ('1800'), ('1830')

SELECT Shift_End
FROM #time
WHERE CAST(SHift_End as int) > 1600 AND TRY_CAST(Shift_End as int) IS NOT NULL

Open in new window

Avatar of UnifiedIS
UnifiedIS

You could easily convert your nvarchar to int and and compare to the current time by turning that into an int

DECLARE @V nvarchar(50)
SET @V = '1600'
SELECT CAST(@V AS int)
SELECT DATEPART(HOUR,GETDATE()) * 100 + DATEPART(MINUTE, GETDATE())
I think the shift_end is part of a work schedule, not the time from a punch clock, correct?
Avatar of moe57

ASKER

yes that is part of the work schedule
>where Shift_End > current datetime.
<correction>  Didn't catch that part, try this...
CREATE TABLE #time (Shift_End nvarchar(10)) 

INSERT INTO #time (Shift_End)
VALUES ('1500'), ('1600'), ('1730'), ('1800'), ('1830')

Declare @current_hhmm int 
SET @current_hhmm = (DATEPART(hh, getdate()) * 100)  + DATEPART(mm, getdate())

SELECT Shift_End
FROM #time
WHERE CAST(SHift_End as int) > @current_hhmm AND TRY_CAST(Shift_End as int) IS NOT NULL

Open in new window

Avatar of moe57

ASKER

just to clarify, i have a date column in the table and the data type for that column datetime but the time is separete and nvarchar
ASKER CERTIFIED SOLUTION
Avatar of UnifiedIS
UnifiedIS

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
i want to pull all records where Shift_End > current datetime.  If shift_end is 1600, then i want to see all records after 1600.

Those contradict each other.  Do you want shift end > current datetime, or current datetime > shift end?
Avatar of moe57

ASKER

thanks