Solved

Source of this error - error converting data type nvarchar to datetime

Posted on 2015-02-10
24
79 Views
Last Modified: 2015-02-10
I keep getting this error when I execute this stored proc:

How to fix?

error converting nvarchar to datetime
0
Comment
Question by:knowlton
  • 13
  • 5
  • 4
  • +1
24 Comments
 
LVL 65

Accepted Solution

by:
Jim Horn earned 300 total points
ID: 40600954
1  Find this proc in your SSMS, right-click: Script Stored Procedure As, Alter to > New Query Editor Window
2  Remove the ALTER PROC line, re-Declare all of the variables, setting them to what you have in the image
3  Execute, verify what line throws the error by double-clicking on the error message.
4  Then ultimately you'll have to identify the values that throw the error by doing some kind of SELECT ... WHERE ISDATE(column name) = 0
0
 
LVL 5

Author Comment

by:knowlton
ID: 40600967
I've done 1 thru 3.


It highlights the SELECT statement (line 9)


Here is what I currently have:

DECLARE
	@LocNums nvarchar(2000) = null,
	@DateBegin datetime = null,
	@DateEnd datetime = null,
	@SortBy nvarchar(50) = null



SELECT
	mainAppr.LastName
	,mainAppr.FirstName
	,mainAppr.UBCID UBCID	
	,lu.LocalNumber LocalNumber
	,lu.ID LocalUnionID
	,ap.Period
	,ap.PercentOfJourneyWages AdvancementPer	
	,aah.dayAdvancementDate AdvancementDate		
FROM UNAdmin.Apprentices mainAppr
	LEFT JOIN UNAdmin.ApprenticeAdvancementHistory aah ON aah.ID = mainAppr.CurrentAdvancementID   
	LEFT JOIN UNAdmin.ApprenticePeriods ap on aah.ApprenticePeriodID = ap.ID
	LEFT JOIN UNAdmin.LocalUnions lu ON lu.ID = mainAppr.LocalUnionID 
	LEFT JOIN UNAdmin.ApprenticeStatus apprStatus ON mainAppr.ApprenticeTypeID = apprStatus.ApprenticeTypeID   
WHERE  apprStatus.IsInProgram = 1 
AND (@LocNums is null OR lu.LocalNumber IN (select value from UNAdmin.unf_SplitToString(@LocNums, ',')))
AND (@DateBegin is null OR aah.dayAdvancementDate >= @DateBegin)
AND (@DateEnd is null OR aah.dayAdvancementDate <= @DateEnd)
ORDER BY 
	CASE 
		WHEN @SortBy = 'Local Number' THEN lu.LocalNumber
        WHEN @SortBy = 'Last Name' THEN mainAppr.LastName
		WHEN @SortBy = 'Advancement Date' THEN aah.dayAdvancementDate
		WHEN @SortBy is null THEN lu.LocalNumber
    END		

Open in new window

0
 
LVL 5

Author Comment

by:knowlton
ID: 40600969
Is this valid TSQL:

(@DateBegin is null OR aah.dayAdvancementDate >= @DateBegin)
0
 
LVL 65

Expert Comment

by:Jim Horn
ID: 40600971
>AND (@DateBegin is null OR aah.dayAdvancementDate >= @DateBegin)
>AND (@DateEnd is null OR aah.dayAdvancementDate <= @DateEnd)
Eyeball aah.dayAdvancementDate and tell us if it's nvarchar or date.
0
 
LVL 45

Expert Comment

by:Vitor Montalvão
ID: 40600975
If the default value is NULL for the dates then don't pass any value. You are passing '''''
Just remove the DateBegin and the DateEnd from the SP call. Or replace the '''' for NULL
0
 
LVL 5

Author Comment

by:knowlton
ID: 40600977
it is a datetime, not null
0
 
LVL 65

Expert Comment

by:Jim Horn
ID: 40600979
btw what's the purpose of @DateBegin=N'''''' in the function call?  
Looks like you're passing a unicode (nvarchar) sting with a couple of ''s in it, and looking at the SP @dateBegin and @dateEnd are datetime's, so that alone could throw the error.

Since the SP defines @dateEnd = NULL, then you should either not set the varible when making the SP call, or set it to NULL instead of N''''''
0
 
LVL 5

Author Comment

by:knowlton
ID: 40600981
is a date time
0
 
LVL 5

Author Comment

by:knowlton
ID: 40600992
btw what's the purpose of @DateBegin=N'''''' in the function call?  

It was me passing in '' as a datetime value (just messing around trying to figure out the error)

I try passing in all nulls and get this:

all nulls
0
 
LVL 65

Expert Comment

by:Jim Horn
ID: 40600996
>It was me passing in '' as a datetime value
There's your problem.  '' is an empty string, and NOT a NULL.  
To pass a NULL, explicitly state NULL.
0
 
LVL 5

Author Comment

by:knowlton
ID: 40601002
Look what happens when I don't even pass in date values:


begin and end date not passed in
0
 
LVL 45

Expert Comment

by:Vitor Montalvão
ID: 40601012
Can you try without that ORDER BY clause?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 5

Author Comment

by:knowlton
ID: 40601037
Can you try without that ORDER BY clause?

It runs then.  : P
0
 
LVL 5

Author Comment

by:knowlton
ID: 40601053
But I still don't know what to fix.

I can't simply remove my order by clause.  I need it.
0
 
LVL 5

Author Comment

by:knowlton
ID: 40601054
What changes do I need to make to be able to use my ORDER BY clause?

It does run ... but if I uncomment the order by clause .. it does not run gives the same error.

DECLARE
	@LocNums nvarchar(2000) = null,
	@DateBegin datetime = null,
	@DateEnd datetime = null,
	@SortBy nvarchar(50) = null



SELECT
	mainAppr.LastName
	,mainAppr.FirstName
	,mainAppr.UBCID UBCID	
	,lu.LocalNumber LocalNumber
	,lu.ID LocalUnionID
	,ap.Period
	,ap.PercentOfJourneyWages AdvancementPer	
	,aah.dayAdvancementDate AdvancementDate		
FROM UNAdmin.Apprentices mainAppr
	LEFT JOIN UNAdmin.ApprenticeAdvancementHistory aah ON aah.ID = mainAppr.CurrentAdvancementID   
	LEFT JOIN UNAdmin.ApprenticePeriods ap on aah.ApprenticePeriodID = ap.ID
	LEFT JOIN UNAdmin.LocalUnions lu ON lu.ID = mainAppr.LocalUnionID 
	LEFT JOIN UNAdmin.ApprenticeStatus apprStatus ON mainAppr.ApprenticeTypeID = apprStatus.ApprenticeTypeID   
WHERE  apprStatus.IsInProgram = 1 
AND (@LocNums is null OR lu.LocalNumber IN (select value from UNAdmin.unf_SplitToString(@LocNums, ',')))
AND (@DateBegin is null OR aah.dayAdvancementDate >= @DateBegin)
AND (@DateEnd is null OR aah.dayAdvancementDate <= @DateEnd)
--ORDER BY 
--	CASE 
--		WHEN @SortBy = 'Local Number' THEN lu.LocalNumber
--        WHEN @SortBy = 'Last Name' THEN mainAppr.LastName
--		WHEN @SortBy = 'Advancement Date' THEN aah.dayAdvancementDate
--		WHEN @SortBy is null THEN lu.LocalNumber
--    END		

Open in new window

0
 
LVL 45

Expert Comment

by:Vitor Montalvão
ID: 40601066
For my understanding the order by columns need to be all from the same datatype since you are using a CASE it expected to return a value from the same type. You can try to convert all non-char fields to varchar.
0
 
LVL 5

Author Comment

by:knowlton
ID: 40601068
Narrowed it down to this line:

            --WHEN @SortBy = 'Advancement Date' THEN aah.dayAdvancementDate


If I uncomment that line it stops working.

DECLARE
	@LocNums nvarchar(2000) = null,
	@DateBegin datetime = null,
	@DateEnd datetime = null,
	@SortBy nvarchar(50) = null



SELECT
	mainAppr.LastName
	,mainAppr.FirstName
	,mainAppr.UBCID UBCID	
	,lu.LocalNumber LocalNumber
	,lu.ID LocalUnionID
	,ap.Period
	,ap.PercentOfJourneyWages AdvancementPer	
	,aah.dayAdvancementDate AdvancementDate		
FROM UNAdmin.Apprentices mainAppr
	LEFT JOIN UNAdmin.ApprenticeAdvancementHistory aah ON aah.ID = mainAppr.CurrentAdvancementID   
	LEFT JOIN UNAdmin.ApprenticePeriods ap on aah.ApprenticePeriodID = ap.ID
	LEFT JOIN UNAdmin.LocalUnions lu ON lu.ID = mainAppr.LocalUnionID 
	LEFT JOIN UNAdmin.ApprenticeStatus apprStatus ON mainAppr.ApprenticeTypeID = apprStatus.ApprenticeTypeID   
WHERE  apprStatus.IsInProgram = 1 
AND (@LocNums is null OR lu.LocalNumber IN (select value from UNAdmin.unf_SplitToString(@LocNums, ',')))
AND (@DateBegin is null OR aah.dayAdvancementDate >= @DateBegin)
AND (@DateEnd is null OR aah.dayAdvancementDate <= @DateEnd)
ORDER BY 
	CASE 
		WHEN @SortBy = 'Local Number' THEN lu.LocalNumber
        WHEN @SortBy = 'Last Name' THEN mainAppr.LastName
		--WHEN @SortBy = 'Advancement Date' THEN aah.dayAdvancementDate
		WHEN @SortBy is null THEN lu.LocalNumber
    END		

Open in new window

0
 
LVL 5

Author Comment

by:knowlton
ID: 40601072
You can try to convert all non-char fields to varchar.


You are talking to a TSQL noob here.

Can you show me what you mean?
0
 
LVL 69

Assisted Solution

by:ScottPletcher
ScottPletcher earned 100 total points
ID: 40601076
ORDER BY
      CASE
            WHEN @SortBy = 'Local Number' THEN lu.LocalNumber
            WHEN @SortBy = 'Last Name' THEN mainAppr.LastName
            WHEN @SortBy = 'Advancement Date' THEN CONVERT(varchar(8),  aah.dayAdvancementDate, 112)
            WHEN @SortBy is null THEN lu.LocalNumber
    END
0
 
LVL 45

Assisted Solution

by:Vitor Montalvão
Vitor Montalvão earned 100 total points
ID: 40601086
As ScottPletcher presented above or you can take that sort independently:
DECLARE
	@LocNums nvarchar(2000) = null,
	@DateBegin datetime = null,
	@DateEnd datetime = null,
	@SortBy nvarchar(50) = null

IF @SortBy = 'Advancement Date'  THEN
  SELECT
	mainAppr.LastName
	,mainAppr.FirstName
	,mainAppr.UBCID UBCID	
	,lu.LocalNumber LocalNumber
	,lu.ID LocalUnionID
	,ap.Period
	,ap.PercentOfJourneyWages AdvancementPer	
	,aah.dayAdvancementDate AdvancementDate		
FROM UNAdmin.Apprentices mainAppr
	LEFT JOIN UNAdmin.ApprenticeAdvancementHistory aah ON aah.ID = mainAppr.CurrentAdvancementID   
	LEFT JOIN UNAdmin.ApprenticePeriods ap on aah.ApprenticePeriodID = ap.ID
	LEFT JOIN UNAdmin.LocalUnions lu ON lu.ID = mainAppr.LocalUnionID 
	LEFT JOIN UNAdmin.ApprenticeStatus apprStatus ON mainAppr.ApprenticeTypeID = apprStatus.ApprenticeTypeID   
WHERE  apprStatus.IsInProgram = 1 
AND (@LocNums is null OR lu.LocalNumber IN (select value from UNAdmin.unf_SplitToString(@LocNums, ',')))
AND (@DateBegin is null OR aah.dayAdvancementDate >= @DateBegin)
AND (@DateEnd is null OR aah.dayAdvancementDate <= @DateEnd)
ORDER BY aah.dayAdvancementDate

ELSE
  SELECT
	mainAppr.LastName
	,mainAppr.FirstName
	,mainAppr.UBCID UBCID	
	,lu.LocalNumber LocalNumber
	,lu.ID LocalUnionID
	,ap.Period
	,ap.PercentOfJourneyWages AdvancementPer	
	,aah.dayAdvancementDate AdvancementDate		
FROM UNAdmin.Apprentices mainAppr
	LEFT JOIN UNAdmin.ApprenticeAdvancementHistory aah ON aah.ID = mainAppr.CurrentAdvancementID   
	LEFT JOIN UNAdmin.ApprenticePeriods ap on aah.ApprenticePeriodID = ap.ID
	LEFT JOIN UNAdmin.LocalUnions lu ON lu.ID = mainAppr.LocalUnionID 
	LEFT JOIN UNAdmin.ApprenticeStatus apprStatus ON mainAppr.ApprenticeTypeID = apprStatus.ApprenticeTypeID   
WHERE  apprStatus.IsInProgram = 1 
AND (@LocNums is null OR lu.LocalNumber IN (select value from UNAdmin.unf_SplitToString(@LocNums, ',')))
AND (@DateBegin is null OR aah.dayAdvancementDate >= @DateBegin)
AND (@DateEnd is null OR aah.dayAdvancementDate <= @DateEnd)
ORDER BY 
	CASE 
		WHEN @SortBy = 'Local Number' THEN lu.LocalNumber
        WHEN @SortBy = 'Last Name' THEN mainAppr.LastName
		WHEN @SortBy is null THEN lu.LocalNumber

    END		

Open in new window

0
 
LVL 5

Author Comment

by:knowlton
ID: 40601097
This seems to work (attempted in the interim between responses):


DECLARE
	@LocNums nvarchar(2000) = null,
	@DateBegin datetime = null,
	@DateEnd datetime = null,
	@SortBy nvarchar(50) = null

SELECT
	mainAppr.LastName
	,mainAppr.FirstName
	,mainAppr.UBCID UBCID	
	,lu.LocalNumber LocalNumber
	,lu.ID LocalUnionID
	,ap.Period
	,ap.PercentOfJourneyWages AdvancementPer	
	,aah.dayAdvancementDate AdvancementDate		
FROM UNAdmin.Apprentices mainAppr
	LEFT JOIN UNAdmin.ApprenticeAdvancementHistory aah ON aah.ID = mainAppr.CurrentAdvancementID   
	LEFT JOIN UNAdmin.ApprenticePeriods ap on aah.ApprenticePeriodID = ap.ID
	LEFT JOIN UNAdmin.LocalUnions lu ON lu.ID = mainAppr.LocalUnionID 
	LEFT JOIN UNAdmin.ApprenticeStatus apprStatus ON mainAppr.ApprenticeTypeID = apprStatus.ApprenticeTypeID   
WHERE  apprStatus.IsInProgram = 1 
AND (@LocNums is null OR lu.LocalNumber IN (select value from UNAdmin.unf_SplitToString(@LocNums, ',')))
AND (@DateBegin is null OR aah.dayAdvancementDate >= @DateBegin)
AND (@DateEnd is null OR aah.dayAdvancementDate <= @DateEnd)
ORDER BY 
	CASE 
		WHEN @SortBy = 'Local Number' THEN lu.LocalNumber
        WHEN @SortBy = 'Last Name' THEN mainAppr.LastName
		WHEN @SortBy = 'Advancement Date' THEN CAST(aah.dayAdvancementDate AS nvarchar)
		WHEN @SortBy is null THEN lu.LocalNumber
    END		

Open in new window

0
 
LVL 45

Expert Comment

by:Vitor Montalvão
ID: 40601102
Good.
You are talking to a TSQL noob here.
You aren't that noob after all ;)
0
 
LVL 5

Author Comment

by:knowlton
ID: 40601108
You aren't that noob after all ;)

How dare you!  : P


Thanks everyone for your help!
0
 
LVL 69

Expert Comment

by:ScottPletcher
ID: 40601146
>> WHEN @SortBy = 'Advancement Date' THEN CAST(aah.dayAdvancementDate AS nvarchar) <<

FYI, be careful when sorting dates in character format.  The default format is typically:
mmm dd yyyy timeAM|PM
which of course does not sort correctly.

I used YYYYMMDD, but that only handles days, of course.  If you need time as well, you'll need to change that to:
WHEN @SortBy = 'Advancement Date' THEN CONVERT(varchar(30),  aah.dayAdvancementDate, 121)




select CAST(getdate() as nvarchar)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now