Select As VarChar But Order By DateTime

Mar 13, 2008

Hello,

I'm trying to CONVERT some DateTime column to VarChar in the SELECT part but still do a DateTime ORDER BY while using a UNION.

In other words, does anyone know how to make this work:


create table #temp1 (
d datetime
)

create table #temp2 (
d datetime
)

insert into #temp1(d)
select '2001-12-12' union
select '2002-11-11'

insert into #temp2(d)
select '2003-10-10' union
select '2004-09-09'


--works fine-------------------------------
select convert(varchar, d, 101) dd from #temp1
order by d
-------------------------------------------



--but can't make this work-------------------

select convert(varchar, d, 101) dd from #temp1
union select convert(varchar, d, 101) dd from #temp2

order by dd -- wrong type of sorting

--order by d-- error

--order by cast(dd as datetime) -- error

-------------------------------------------

drop table #temp1
drop table #temp2


I would really appreciate your help.

Thanks in advance,
Thomas

View 5 Replies


ADVERTISEMENT

ORDER BY [Date] Isn't Working Since It's Not A DateTime (it's A Varchar!)

Mar 4, 2004

Hi everyone.

I know, I know, it should have been a datetime from the start...but here's the problem.

I'm trying to sort by my date field but because it looks like: "04/03/2004 12:14:21 PM" it's not ordering it properly using:

ORDER BY [Date]

Are there any work arounds for this? Is there some way of doing:

ORDER BY covert(datetime, [Date], 103) or something?

Cheers
Andrew

View 3 Replies View Related

How To Convert Datetime From Varchar To Datetime

Sep 11, 2007

hi,
How do i convert a varchar field into the datetime data type? the reason i need this lies in the requirement that in the earlier data base the column that is hlding the date value is having the data type as varchar. and in the new design the column data type is datetime. i am using sql scripts for the data migration from the older design to the newer and got stuck with this datetime convertion issue. do let me know the best possible solution.

following are the sample data that is theer in the older table for the date.


12/12/2003
1/13/2007
01132004
1-1-2004
1.2.2001



there is no uniformity of the data that is stored currently.



thnkx in adv.
rahul jha

View 11 Replies View Related

Default Sort Order - Open Table - Select Without Order By

Mar 27, 2008

Hi!

I recently run into a senario when a procedure quiered a table without a order by clause. Luckily it retrived data in the prefered order.

The table returns the data in the same order in SQL Manager "Open Table"

So I started to wonder what deterimins the sort order when there is no order by clause ?

I researched this for a bit but found no straight answers. My table has no PK, but an identiy column.

Peace.

/P

View 5 Replies View Related

How To Order By Varchar

Dec 30, 2005

Dear all,

I have a varchar field which have data:

ID_trans
---------
T1
T10
T11
T2
T3
everytime i use select statement with order by, the result is above

Does somebody know..? HOw to make the result like below

ID_trans
---------
T1
T2
T3
T10
T11

Sorry i'm not good in english...

Thanks

View 10 Replies View Related

ORDER BY &&<VarChar Field&&>

May 23, 2006

Hi group,

I've got a table with two columns named [Year] and [Month]. They are both defined as VarChar.

Question:
Is it possible to ORDER THEM as if they where of type DateTime?

EG
select [year], [month]
from tbl_WeightedAverageGenerated
where [Year] = 2006
ORDER BY [Month]

Returns:
2006, 10
2006, 11
2006, 12
2006, 5
2006, 6
etc...


I need it to return:
2006 5
2006 6
2006 7
2006 8
2006 9
2006 10

2006 11

2006 12

Is this possible....and how??

TIA

Regards,

SDerix

View 1 Replies View Related

HOw To Order Fields Of Type Varchar?

Mar 22, 2000

I have a varchar field which holds IDs like (1, 3, 5, 19, 23) when I order it, i get it ordered in ASCII order like (1, 19, 23, 3, 5) rather than (1, 3, 5, 19, 23) Even if I convert it to int, I won't be able to order it.

is there any way I can order a varchar field numerically?

Angel

View 1 Replies View Related

Convert Varchar To Datetime!!!

Apr 20, 2005

Hi:
I have a column call Date_Sent (28/02/2004)(dd/mm/yyyy) format as varchar at beginning. I want to convert to other column as datetime. 
I use Query like:
SELECT
CAST(SUBSTRING(Date_Sent,1,2)as int) + '/' +CAST(SUBSTRING(date_sent,4,2) as int) + '/' +CAST(SUBSTRING(DATE_SENT,7,4) as int)
From MyTable
It is not working, anybody can give me some advise!
thanks!
 
 

View 4 Replies View Related

Converting Varchar To DateTime

Sep 17, 2007



Hi,

I wanted to convert the varchar to date time and here is what i am doing


DECLARE @dt VARCHAR(20)

SET @dt = '20070111' -- YYYYMMDD format

select CONVERT(datetime, @dt, 120)


This works perfectly fine and the result would be- 2007-01-11 00:00:00.000

But if i changed my datetime format from YYYYMMDD to YYYYMMDDHHMM then this is failing and throwing

"Conversion failed when converting datetime from character string."

Can any one please let me know how do we achieve this?



~Mohan

View 3 Replies View Related

Converting Varchar To Datetime

Oct 23, 2007



Hi,


I'm facing a small issue with date conversions. It would have been great if someone could help me out. I have a field in my database (SQL Server 2000) called SavDateTime of type varchar(50). I store dates in this field in the format "dd/MM/yy hh:mms". A sample date would be "23/10/2007 10:15:30 AM". Now I need to have an order by for this field, say like,


select * from sample order by SavDateTime desc


When I execute this query I get an error saying "The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.". I tried using the convert method also like CONVERT(DATETIME,SavDateTime,103), but the problem still exists. It would have been helpful if you could provide me with a solution to this problem.



Thanks & Regards,
Frens

View 7 Replies View Related

Correctly ORDER BY Date That Has Been Cast As A Varchar

May 23, 2008

how do you get it to sort correctly for the date? at the minute its sorting on the characters rather than actual date value





Code Snippet
INSERT INTO @TempItems (OrderID)
SELECT OrderID
FROM Orders o
INNER JOIN Customers c ON c.CustomerID = o.CustomerID
INNER JOIN Employees e ON e.EmployeeID = o.EmployeeID
ORDER BY
CASE @SortOrder --Order ASC
WHEN 0 THEN cast(OrderID as varchar(100))
WHEN 1 THEN cast(c.CompanyName as varchar(100))
WHEN 2 THEN cast(e.FirstName as varchar(100))
WHEN 3 THEN cast(o.OrderDate as varchar(100))
WHEN 4 THEN cast(o.RequiredDate as varchar(100))
WHEN 5 THEN cast(o.ShippedDate as varchar(100))
ELSE '1'
END,

View 4 Replies View Related

VarChar Auto Updating DateTime

Apr 12, 2005

I have a textbox that is receiving a date in the format  mm/dd/yyyy.  The field in the database is VarChar size 10.  I purposely don't want to use the DateTime data type for various reasons.  When I extract the text from that textbox:
Example:4/11/2005
I do my INSERT.  When I look in the database at that field, it shows up like:April 11, 2005 12
The database's field is VarChar! How/why is it doing automatic DateTime formatting?

View 3 Replies View Related

Will Varchar Automatic Convert Into Datetime ?

Aug 8, 2006

hi, good day, if i have a table as follow:

Create table test
(
student_name varchar(20),
student id varchar(20),
register_dt varchar(50)
)


and insert data like


insert into test values('rebecca','0001','2006-08-08 12:15:03')


after all , i would like to query the data and insert into another table say data_tbl where it define as follow

Create table data_tbl
(

student_name varchar(20),
student id varchar(20),
register_dt datetime
)


would the test table regiter_dt auto convert into datetime format or we need to convert it before insert into data_tbl table?

View 3 Replies View Related

How To Cast A Varchar Column To DateTime

Jan 21, 2012

Below is my query.Its working great if i remove ,Cast(C.ClassTime as time) as StartDate.But when i use this i get an error as The conversion of a varchar data type to a datetime data type resulted in an out-of-range value My ClassName is a varchar.Whose definition i cant change to DateTime now.But i want to cast it to DateTime.

Code:
Select C.ClassID as Appointment_Id,C.ClassName as Appoitment_Descr,Cast(C.ClassTime as time) as StartDate,C.EndClassTime as EndDate, 'Class' as Type
From Dojo D inner join DojoClass C on D.SchoolID = C.DojoSchoolID
Where D.SchoolID = @DojoID
and C.Days like'%' + @Days + '%'
Union
Select E.DojoEventID as Appointment_Id,E.EventName as Appoitment_Descr , E.EventStartDate as StartDate , E.EventEndDate as EndDate,'Event' as Type
From Dojo D inner join DojoEvent E on E.DojoID = D.SchoolID
Where D.SchoolID = @DojoID and @Date
Between E.EventStartDate and E.EventEndDate

how can i cast it correctly?

View 1 Replies View Related

T-SQL (SS2K8) :: Changing Varchar To Datetime?

Oct 2, 2014

I can't get a varchar to datetime conversion to work. The varchar data is in the form yyyymmddhhmi

I tried convert(datetime, '200508310926')

also tried cast('200508310926' as datetime) both have error "Conversion failed when converting date and/or time from character string"

Is there a format code that needs to be there? If so, I can't figure out what it should be.

I eventually need to convert these to dates and compare them to getdate, example:

...where convert(datetime, dtfield) >= getdate()-1

View 7 Replies View Related

How To Convert A Varchar To A Yyyy-mm-dd Datetime?

May 27, 2008

Hi All,

I have a table called Table1 with a field Date (varchar type). The records are like this;

05/21/08
07/02/08
06/04/08
06/10/08


I want to convert the above into datetime (yyyy-mm-dd format)....in the above example my output should be;

2008-05-21
2008-07-02
2008-06-04
2008-06-10

How can i do this?

Please help.

Zee...

View 2 Replies View Related

Math Over Datetime In Varchar Format??

Jun 17, 2008

Hello,

I have this column of time values:
00:00:03.3592675
00:00:00
00:00:03.8592515
00:00:03.6873820
00:00:03.8436270
00:00:03.3436430

It is in varchar format. I tried converting it to datetime but get an invalid format error message.

How can I sum up these values and average them out?

Thanks!

--PhB

View 1 Replies View Related

Convert Varchar To Datetime Datatype?

Jun 19, 2014

I have a column on my table with the varchar(50) datatype. The whole column has the value 2014-04-31

I want to Convert the varchar(50)datatype to datetime datatype.

The table name is called - dbo.pracs

the column name is - LastDatUpaded

View 6 Replies View Related

It Can't Convert Varchar To A Datetime Type

Dec 14, 2007

I have this procedure and it can't convert this date to datetime type:

Exec scnr.prc_tblScannersReemplazarClasificacion
'CERVEZA ',
'CERVEZA',
'ENV VAC ',
'ENVASE VACIO',
'NULL',
'NO aplica',
'NULL',
'NO aplica',
'1-8-2007',
'10-12-2007',
'ISCRacajina';

and after that i tried to execute it, but I changed the date like next:

Exec scnr.prc_tblScannersReemplazarClasificacion
'CERVEZA ',
'CERVEZA',
'ENV VAC ',
'ENVASE VACIO',
'NULL',
'NO aplica',
'NULL',
'NO aplica',
'8-1-2007',
'12-10-2007',
'ISCRacajina';

and the procedure reseive this parameter:

CREATE PROCEDURE scnr.prc_tblScannersReemplazarClasificacion(@tipoclasificacion varchar(200),
@categoriaV varchar(200),
@categoriaN varchar(200),
@subcategoriaV varchar(200),
@subcategoriaN varchar(200),
@tipoV varchar(200),
@tipoN varchar(200),
@subtipoV varchar(200),
@subtipoN varchar(200),
@fechascanner datetime,
@fechaingreso datetime,
@usuarioscanner varchar(200) )


The error is:
Msg 8114, Level 16, State 5, Procedure prc_tblScannersReemplazarClasificacion, Line 0
Error converting data type varchar to datetime.

Why can't this procedure reseive these dates?
What can I do?

Help me...

View 3 Replies View Related

PHP/MS SQL - Automatic Formatting: Varchar, Datetime

Apr 10, 2008

Hi,I want to change 2 default behaviors of ms-sql server within a connection.1. All varchar (etc.) fields should be returned as UTF-8.I know about field attribute collation and convert function,but I want simple query like:SELECT * FROM table;to return all varchars as UTF-8, no matter how the fields weredefined and which collation.In MySQL I execute: "SET NAMES 'utf-8';" after connecting to serverIn PgSQL I use native function: pg_set_client_encoding()2. Default datetime format is sth like this: "Apr 20 2008 12:01PM"I just want all datetimes fields were returned as:"2008-04-20 12:01:02"I can do that with function convert() (style=20) but I want(as in question above) a simple query like:SELECT * FROM table;to return date and time formatted as described above.In MySQL and PgSQL the format "2008-04-20 12:01:02" is the defaultone.Is it possible to do that? If yes, please tell me how can I do that?Wladyslaw

View 3 Replies View Related

Comparing A Varchar And A Datetime Field

Feb 22, 2008



Hi,
I have a varchar field named FinancialYTDCode containing data in the format 2007F or 2008F. I want to only select the rows with the FinancialYTDCode that is the same as the current year.

Could someone please show me how I write this in my script.
Thanks

View 9 Replies View Related

Ho To Convert Varchar Datatype Into Datetime

Aug 22, 2007




declare @a varchar(10)
select @a= shiftstarttime from o_parameter
print @a

declare @b varchar(10)
select @b= shiftendtime from o_parameter
print @b


declare @dt varchar(20)
set @dt=Left(getdate(),12)

print @dt

declare @dt1 varchar(20)
set @dt1=Left(dateadd(dd, 1,getdate()),12)
print @dt1

declare @dt3 varchar(20)

set @dt3= @dt1 + space(0) + @a

print @dt3

declare @dt4 varchar(20)

set @dt4= @dt + space(0) + @b

print @dt4




output of above script is as fallow
09.30am
06.30pm
Aug 22 2007
Aug 23 2007
Aug 23 2007 09.30am
Aug 22 2007 06.30pm

now i want to convert @dt3 and @dt4 into datetime .

because i wnat to calculate datedifference in hours by using this function
SET @in_hour=DATEDIFF (HH ,@D1,@D2)

where @D1 and @D2 are datetime parameters.

but how can i get @dt3 and @dt4 into datetime so i can pass it to DATEDIFF() function.

so plz Guide me. or if u know how to write it then plz write here

i already use cast for it but it doesn't work.

so plz reply urgently.








View 2 Replies View Related

Datetime And Varchar Conversion Issues

Jan 30, 2008

Basically, I'm trying to take two dates and find the difference in hours b/t the two, sql server 2000. I've tried change the variables out from datetime to varchars even though it shouldn't matter. When I put the block of code out of the stored procedure and run it in line it works fine, I'M LOST.........

I get the errors everytime it runs into the first block, I get the error again when the block is hit again farther down in the procedure. I get:

Server: Msg 242, Level 16, State 3, Procedure tmpRyan_spRail_Job_NoMovement, Line 211
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
Server: Msg 242, Level 16, State 1, Procedure tmpRyan_spRail_Job_NoMovement, Line 360
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
ERR dates Aug 4 2005 11:16PM.
Server: Msg 242, Level 16, State 3, Procedure tmpRyan_spRail_Job_NoMovement, Line 211
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
Server: Msg 242, Level 16, State 1, Procedure tmpRyan_spRail_Job_NoMovement, Line 360
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
ERR dates Aug 3 2005 12:35PM.
Server: Msg 241, Level 16, State 1, Procedure tmpRyan_spRail_Job_NoMovement, Line 211
Syntax error converting datetime from character string.

Code:

Declare
,@CodePair varchar(10
,@CodePairTimeDiff dec ,
@tmpTimeVar datetime ,
@tmpTimeCharVar varchar(30)


IF @NextStatusDate IS NOT NULL AND @StatusDate IS NOT NULL
BEGIN
set @tmpTimeCharVar = DATEDIFF(SECOND, @NextSTatusDate, @StatusDate)
set @tmpTimeVar =
(
CASE WHEN @tmpTimeCharVar/3600<10 THEN '0' ELSE '' END
+ RTRIM(DATEDIFF(SECOND,@NextSTatusDate, @StatusDate)/3600)
+ ':' + RIGHT('0'+RTRIM((@tmpTimeCharVar % 3600) / 60),2)
+ ':' + RIGHT('0'+RTRIM((@tmpTimeCharVar % 3600) % 60),2)
)
END
IF @@ERROR <>0
PRINT 'ERR dates' + Convert(varchar(20), @NextStatusDate) + '.'


inside update statement

,CodePairTimeDiff = CONVERT(dec, (100 * DATEPART(HOUR, @tmpTimeVar)
+ DATEPART(MINUTE, @tmpTimeVar))) / 60

View 12 Replies View Related

SQL 2012 :: Conversion Of Varchar To Datetime - Getdate?

Oct 2, 2014

When you converting varchar to date time

SELECT convert(varchar,getdate())

What is the getdate here

i.e. we are converting any value to today's date

View 9 Replies View Related

SQL Server 2012 :: Converting Varchar To Datetime?

Mar 19, 2015

I am using a custom sql query to import data into Tableau. Problem is I need to change the varchar column data in SQL currently returning 18/01/2014 08:35:13 as a format into the date format 05/21/2014 3:55:51 PM before I can use it.

View 9 Replies View Related

SQL Server 2012 :: Varchar To Datetime Conversion

Aug 14, 2015

I have column moddat which is of varchar(10,null)

Here is my data:
20020415
20020508
19991104
19990701
20040514
20021112
20020124
19990628
20020514
20010822

I want those data in this format YYYY-MM-DD

How to convert varchar to datetime?

View 2 Replies View Related

Converting Varchar Column 07MAR2012:00:00:00.000 Into Datetime

Jun 14, 2015

I have a column in a sql Table with a datatype nvarchar 255 and the value in the column is 07MAR2012:00:00:00.000. I want to convert into a datetime.

View 4 Replies View Related

DB Design :: Optimize A Query That Uses A Varchar Column That Is Used In Order By Clause

May 5, 2015

I am querying a tableA with 1.8 million rows, it has id as its primary key and is a clustered index. I need to select all rows where I order by lastname. Its taking me 45 seconds. Is there anything i can do to optimize the query.Will creating a fulltext index on lastname If so, can you give me an example on how to create a full text index on lastname?

[Project1].[Id] AS [Id], 
[Project1].[DirectoryId] AS [DirectoryId], 
[Project1].[SPI] AS [SPI], 
[Project1].[FirstName] AS [FirstName], 
[Project1].[LastName] AS [LastName], 
[Project1].[NPI] AS [NPI], 
[Project1].[AddressLine1] AS [AddressLine1], 
[Project1].[AddressLine2] AS [AddressLine2], 

[code]...

View 5 Replies View Related

Specify Order For Select Results, Order By: Help!

Nov 17, 2006

Lets say I have a table named [Leadership] and I want to select the field 'leadershipName' from the [Leadership] Table.

My query would look something like this:

Select leadershipName
From Leadership

Now, I would like to order the results of this query... but I don't want to simply order them by ASC or DESC. Instead, I need to order them as follows:

Executive Board Members, Delegates, Grievance Chairs, and Negotiators

My question: Can this be done through MS SQL or do I need to add a field to my [Leadership] table named 'leadershipImportance' or something as an integer to denote the level of importance of the position so that I can order on that value ASC or DESC?

Thanks,

Zoop

View 1 Replies View Related

Error Converting Data Type Varchar To Datetime.

Feb 16, 2007

Hi,
It is not exactly what I stated in the subject - It's an outcome - exception thrown while executing non-query command.
I get this exception when I try to execute my stored procedure that takes datetime as one of its parameters.
I am using dataset designer to create table adapters and build queries. Then I simply use objectdatasource component that uses one of the table adapters and bind it to for example a detailsview control.
When I run this in debug mode and trace the objects everything looks perfect including these datetime parameters. It is sql server that throws the exception. I ran the sql profiler to see what exactly is going on, and I captured the command that is sent by ADO - it's broken into several lines right in the middle of my datetime parameters... this is the source of the problem. Everything is working fine when I take this command and execute it as a single line in the sql management studio.
Is there anything about ADO that I do not know?

View 2 Replies View Related

Issue: How To Convert A Database Field From Varchar To Datetime..?

Jul 22, 2005

Can anyone help me on this!I've got more than a 1000 records in  a SQL server database.The problem is that the the date field is set to varchar, and that gives a lot of trouble. (for example by sorting a table, it's a mess)How can i make sure that i will have a table with the date field set to datettime en that those 1000 records still will be in it. thanks in advance!

View 1 Replies View Related

Error Converting Data Type Varchar To Datetime

Dec 4, 2004

hi
i want to pass a datetime variable from a asp page to MSSQL through a stored procedure, & i get this error:

Microsoft OLE DB Provider for ODBC Drivers (0x80040E07)
[Microsoft][ODBC SQL Server Driver][SQL Server]Error converting data type varchar to datetime.

this is the code that i use in page:

strsql="sp_inventory @timee=' " & RecievedDate & " ' "

also i use this one:
but i still get this error

strsql="sp_inventory @timee=' " & cdate(RecievedDate) & " ' "


this is maybe useful that i get this errot on some PCs, not all the computeres.
sometimes work well, & sth not work.

View 2 Replies View Related

Error Converting Data Type Varchar To Datetime.

Dec 22, 2004

Here is the stored procedure
the data type for the column b_trn_tentdte is decimal(8,0).

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

ALTER Procedure Prc_New_cus_wo_prev_posted
@b_trn_tendte_Beg_Date datetime
,@b_trn_tendte_End_Date datetime
@b_trn_tendte_Beg_Date1 datetime
,@b_trn_tendte_End_Date2 datetime

as

declare @Beg_tentdte datetime
declare @End_tentdte datetime
declare @Beg_tentdte1 datetime
declare @Beg_tentdte2 datetime

set @Beg_tentdte = convert(varchar(10), @b_trn_tendte_Beg_Date, 112)
set @End_tentdte = convert(varchar(10), @b_trn_tendte_End_Date, 112)
set @Beg_tentdte1 = convert(varchar(10), @b_trn_tendte_Beg_Date1, 112)
set @Beg_tentdte2 = convert(varchar(10), @b_trn_tendte_End_Date2, 112)


/* this query looks for customers with posted
transactions but none prior to the date range
in question */

Select distinct b_cus_cname
from
bar_cus_db_rec
,bar_trn_db_rec b
where b.b_trn_instid = ''
and b.b_trn_instid = b_cus_instid
and b.b_trn_actid = b_cus_cusid
and convert(varchar(10), b.b_trn_tentdte) between @Beg_tentdte and @End_tentdte
and not exists (select c.b_trn_actid
from bar_trn_db_rec c
where c.b_trn_instid = b.b_trn_instid
--and c.b_trn_tentdte between 19970901 and 20030229
and convert(varchar(10), c.b_trn_tentdte) between @Beg_tentdte1 and @Beg_tentdte2
and c.b_trn_actid = b.b_trn_actid)

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

every time I run the query, I get this error message:
Error converting data type varchar to datetime.

thanks for your assistance.

View 5 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved