Thursday, March 29, 2012
Date question
it to datetime data type ?
pls let me knowDo you need to jsut convert it within a query, you can use Cast of Convert
for that.
If you need to convert the column's data type, You have two options.
1) in T-SQL add the new column, do an update to move the data over, drop the
old column, then rename the new column
2) in Enterprise Manager change the data type and it will create a script
for you.
"mvp" <mvp@.discussions.microsoft.com> wrote in message
news:BAD8F615-56DF-47EB-93A7-26A8AC5C0920@.microsoft.com...
> Hello everybody i do have varchar column with DD-MM-YYYY. How can i
> convert
> it to datetime data type ?
> pls let me know
Tuesday, March 27, 2012
date query question
I have the following database:
[id] [int] IDENTITY(1,1) NOT NULL,
[id_number] [varchar](50) NULL,
[company_reg_number] [int] NULL,
[resourceid] [int] NULL,
[status] [int] NULL,
[subject] [varchar](50) NULL,
[description] [text] NULL,
[label] [int] NULL,
[starttime] [datetime] NULL,
[endtime] [datetime] NULL,
[schedule_type] [varchar](255) NULL,
[location] [varchar](50) NULL,
[allday] [bit] NULL,
[eventtype] [int] NULL,
[recurrenceinfo] [text] NULL,
[reminderinfo] [text] NULL,
[staff_file_no] [int] NULL,
and I want to query the date range between starttime and endtime. I have created this code in C# but I don't know how to create
the stored procedure:
private void getScheduleList()
{
data_table = new DataTable();
// sql_connection = new SqlConnection("Data
Source=.\\SQLEXPRESS;initial catalog=shefa;integrated security=true");
sql_connection = new SqlConnection(public_var.sql_connection);
sql_command = new SqlCommand("sp_get_staff_schedule", sql_connection);
sql_command.CommandType = CommandType.StoredProcedure;
sql_command.Parameters.Add("@.id_number", SqlDbType.VarChar).Value = cboDoctor.Text.Substring(0, 9);
sql_command.Parameters.Add("@.starttime", SqlDbType.DateTime).Value = dateSchedule.Value;
if (cboRange.Text == "DAY")
sql_command.Parameters.Add("@.endtime", SqlDbType.DateTime).Value = dateSchedule.Value;
else if (cboRange.Text == "WEEK")
sql_command.Parameters.Add("@.endtime", SqlDbType.DateTime).Value = dateSchedule.Value.AddDays(7);
else if (cboRange.Text == "MONTH")
sql_command.Parameters.Add("@.endtime", SqlDbType.DateTime).Value = dateSchedule.Value.AddDays(31).ToShortDateString();
else
sql_command.Parameters.Add("@.endtime", SqlDbType.DateTime).Value = dateSchedule.Value;
data_adapter = new SqlDataAdapter(sql_command);
data_adapter.Fill(data_table);
dataSchedule.DataSource = data_table;
dataSchedule.Columns[0].HeaderText = "Type";
dataSchedule.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft;
dataSchedule.Columns[0].Width = 180;
dataSchedule.Columns[1].HeaderText = "Staff Name";
dataSchedule.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft;
dataSchedule.Columns[1].Width = 180;
dataSchedule.Columns[2].HeaderText = "From";
dataSchedule.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
dataSchedule.Columns[2].DefaultCellStyle.Format = "ddd dd MMM yyyy HH:mm";
dataSchedule.Columns[2].Width = 130;
dataSchedule.Columns[3].HeaderText = "To";
dataSchedule.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
dataSchedule.Columns[3].DefaultCellStyle.Format = "ddd dd MMM yyyy HH:mm";
dataSchedule.Columns[3].Width = 130;
}
NOTE: I only want to create the date part (time must be ignored) so if user selected dates between 9/11/2007 and 9/12/2007 it should list all records regardless of the time.
Please post the stored procedure () code so that we may better help you.
Most likely, you want the WHERE clause to be something like this:
WHERE ( StartTime >= ( dateadd( day, 0, datediff( day, 0, @.StartTime )))
AND EndTime < ( dateadd( day, 0, datediff( day, 0, ( @.StartTime + 1 ))))
)
|||You can Use " CONVERT | CAST " to make the data's format be consistency.
such as your case, you can trythe sample code as below:
Where 1=1
and convert (char,starttime,103) >= @.starttime
and convert (char,endtime,103) <= @.endtime
maybe it won't get the best efficiency.
hoping this can help u.
Best Regrades,
Hunt .
|||One of the significant problems with using CAST() or CONVERT() in that manner, is that when you wrap the column with a function like that, it negates the possibility of using indexing.
As Hunt indicated -"it won't get the best efficinecy." In fact, if the table is large, it will be totally frustrating
|||I've posted a better solution here. It's faster and will use indexes when they're present.
Sean
date query question
I have the following database:
[id] [int] IDENTITY(1,1) NOT NULL,
[id_number] [varchar](50) NULL,
[company_reg_number] [int] NULL,
[resourceid] [int] NULL,
[status] [int] NULL,
[subject] [varchar](50) NULL,
[description] [text] NULL,
[label] [int] NULL,
[starttime] [datetime] NULL,
[endtime] [datetime] NULL,
[schedule_type] [varchar](255) NULL,
[location] [varchar](50) NULL,
[allday] [bit] NULL,
[eventtype] [int] NULL,
[recurrenceinfo] [text] NULL,
[reminderinfo] [text] NULL,
[staff_file_no] [int] NULL,
and I want to query the date range between starttime and endtime. I have created this code in C# but I don't know how to create
the stored procedure:
private void getScheduleList()
{
data_table = new DataTable();
// sql_connection = new SqlConnection("Data
Source=.\\SQLEXPRESS;initial catalog=shefa;integrated security=true");
sql_connection = new SqlConnection(public_var.sql_connection);
sql_command = new SqlCommand("sp_get_staff_schedule", sql_connection);
sql_command.CommandType = CommandType.StoredProcedure;
sql_command.Parameters.Add("@.id_number", SqlDbType.VarChar).Value = cboDoctor.Text.Substring(0, 9);
sql_command.Parameters.Add("@.starttime", SqlDbType.DateTime).Value = dateSchedule.Value;
if (cboRange.Text == "DAY")
sql_command.Parameters.Add("@.endtime", SqlDbType.DateTime).Value = dateSchedule.Value;
else if (cboRange.Text == "WEEK")
sql_command.Parameters.Add("@.endtime", SqlDbType.DateTime).Value = dateSchedule.Value.AddDays(7);
else if (cboRange.Text == "MONTH")
sql_command.Parameters.Add("@.endtime", SqlDbType.DateTime).Value = dateSchedule.Value.AddDays(31).ToShortDateString();
else
sql_command.Parameters.Add("@.endtime", SqlDbType.DateTime).Value = dateSchedule.Value;
data_adapter = new SqlDataAdapter(sql_command);
data_adapter.Fill(data_table);
dataSchedule.DataSource = data_table;
dataSchedule.Columns[0].HeaderText = "Type";
dataSchedule.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft;
dataSchedule.Columns[0].Width = 180;
dataSchedule.Columns[1].HeaderText = "Staff Name";
dataSchedule.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft;
dataSchedule.Columns[1].Width = 180;
dataSchedule.Columns[2].HeaderText = "From";
dataSchedule.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
dataSchedule.Columns[2].DefaultCellStyle.Format = "ddd dd MMM yyyy HH:mm";
dataSchedule.Columns[2].Width = 130;
dataSchedule.Columns[3].HeaderText = "To";
dataSchedule.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
dataSchedule.Columns[3].DefaultCellStyle.Format = "ddd dd MMM yyyy HH:mm";
dataSchedule.Columns[3].Width = 130;
}
NOTE: I only want to create the date part (time must be ignored) so if user selected dates between 9/11/2007 and 9/12/2007 it should list all records regardless of the time.
Please post the stored procedure () code so that we may better help you.
Most likely, you want the WHERE clause to be something like this:
WHERE ( StartTime >= ( dateadd( day, 0, datediff( day, 0, @.StartTime )))
AND EndTime < ( dateadd( day, 0, datediff( day, 0, ( @.StartTime + 1 ))))
)
|||You can Use " CONVERT | CAST " to make the data's format be consistency.
such as your case, you can trythe sample code as below:
Where 1=1
and convert (char,starttime,103) >= @.starttime
and convert (char,endtime,103) <= @.endtime
maybe it won't get the best efficiency.
hoping this can help u.
Best Regrades,
Hunt .
|||One of the significant problems with using CAST() or CONVERT() in that manner, is that when you wrap the column with a function like that, it negates the possibility of using indexing.
As Hunt indicated -"it won't get the best efficinecy." In fact, if the table is large, it will be totally frustrating
|||I've posted a better solution here. It's faster and will use indexes when they're present.
Sean
sqlDate query
CREATE TABLE tblA (
fillDated datetime NULL ,
fillDate varchar (10)
)
Sample data:
fillDated fillDate
1/13/2006 1/13/2006
12/19/2005 12/19/2005
I would like to query those records where the date is >= today's date.
Say today's date is 1/13/2006.
From the above data, I would like the result to be
1/13/2006 1/13/2006
When I do the following
select tblA.filldated, tblA.filldate,getdate()
from tblA
where tblA.filldated >= getdate()
--> the result is NO record
when I do the following:
select tblA.filldated, tblA.filldate,getdate()
from tblA
where filldate >= convert(varchar(10),getdate(),101)
--> the result is
1/13/2006 1/13/2006
12/19/2005 12/19/2005 --> wrong, because 12/19/2005 is < 1/13/2006
How can I query the table so that I will get the following as the result ?
1/13/2006 1/13/2006
Thank you.filldated >= getdate() won't work because getdate() will return date
and time so getdate > filldated
filldate >= convert(varchar(10),getdate(),101) is comparing two
strings to see if they are >= then each other, not really what you want
to do is it?|||> filldate >= convert(varchar(10),getdate(),101) is comparing two
> strings to see if they are >= then each other, not really what you want
> to do is it?
No, I want the result to be
1/13/2006 1/13/2006
How can I do that ?
Thanks.
"Gerard" <g.doeswijk@.gmail.com> wrote in message
news:1137168331.130329.120930@.f14g2000cwb.googlegroups.com...
> filldated >= getdate() won't work because getdate() will return date
> and time so getdate > filldated
> filldate >= convert(varchar(10),getdate(),101) is comparing two
> strings to see if they are >= then each other, not really what you want
> to do is it?
>|||http://groups.google.com/group/micr...ring+&start=10&|||Thanks.
I solved the problem by using the following query:
select tblA.filldated, tblA.filldate,getdate()
from tblA
where datediff(day,getdate(),filldated) >= 0
"Gerard" <g.doeswijk@.gmail.com> wrote in message
news:1137170228.372663.107310@.g49g2000cwa.googlegroups.com...
> http://groups.google.com/group/micr...ring+&start=10&
>sql
Sunday, March 11, 2012
Date frustration
Initially I setup my dates in a varchar field, now I need them in a datetime
field...
I have the following query that is acting funny,
UPDATE tblEmpPersonalInfo SET
SepDate = EmpSWVTCSepDate
This query will not successfully run, giving me this error,
The conversion of a char data type to a datetime data type resulted in an
out-of-range datetime value.
The statement has been terminated.
But, if I edit the query like this,
UPDATE tblEmpPersonalInfo SET
SepDate = EmpSWVTCSepDate
WHERE EmpID = 'aa381234'
then the query will work fine... I don't want to have to run the query for
every employee in the database, so how can I do this?
Thanks,
DrewUse ISDATE() function to identify if the data in the column are truly date
values. Check out SQL Server Books Online for more details on this function.
Anith|||Hi
Check that all the values in the EmpSWVTCSepDate column are actually valid
dates.
SELECT * FROM tblEmpPersonalInfo
WHERE ISDATE(EmpSWVTCSepDate) = 0
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"Drew" <drew.laing@.NOswvtc.dmhmrsas.virginia.SPMgov> wrote in message
news:e6aUZElAFHA.2792@.TK2MSFTNGP15.phx.gbl...
> I screwed up when building my application, now I need to try to fix it...
> Initially I setup my dates in a varchar field, now I need them in a
datetime
> field...
> I have the following query that is acting funny,
> UPDATE tblEmpPersonalInfo SET
> SepDate = EmpSWVTCSepDate
> This query will not successfully run, giving me this error,
> The conversion of a char data type to a datetime data type resulted in an
> out-of-range datetime value.
> The statement has been terminated.
> But, if I edit the query like this,
> UPDATE tblEmpPersonalInfo SET
> SepDate = EmpSWVTCSepDate
> WHERE EmpID = 'aa381234'
> then the query will work fine... I don't want to have to run the query for
> every employee in the database, so how can I do this?
> Thanks,
> Drew
>|||Thanks... There was 1 invalid date in there, 10-10--2003
Drew
"Mike Epprecht (SQL MVP)" <mike@.epprecht.net> wrote in message
news:u4k2MPlAFHA.2604@.TK2MSFTNGP10.phx.gbl...
> Hi
> Check that all the values in the EmpSWVTCSepDate column are actually valid
> dates.
> SELECT * FROM tblEmpPersonalInfo
> WHERE ISDATE(EmpSWVTCSepDate) = 0
> Regards
> --
> Mike Epprecht, Microsoft SQL Server MVP
> Zurich, Switzerland
> IM: mike@.epprecht.net
> MVP Program: http://www.microsoft.com/mvp
> Blog: http://www.msmvps.com/epprecht/
> "Drew" <drew.laing@.NOswvtc.dmhmrsas.virginia.SPMgov> wrote in message
> news:e6aUZElAFHA.2792@.TK2MSFTNGP15.phx.gbl...
> datetime
>|||Drew,
1 - Update those without problem
UPDATE tblEmpPersonalInfo SET
SepDate = EmpSWVTCSepDate
where isdate(EmpSWVTCSepDate) = 1
2 - Identify those with problem, correct the problem and update them again.
select * from tblEmpPersonalInfo
where isdate(EmpSWVTCSepDate) = 0
-- fix the problem
...
UPDATE tblEmpPersonalInfo SET
SepDate = EmpSWVTCSepDate
where isdate(EmpSWVTCSepDate) = 1 and SepDate is null
AMB
"Drew" wrote:
> I screwed up when building my application, now I need to try to fix it...
> Initially I setup my dates in a varchar field, now I need them in a dateti
me
> field...
> I have the following query that is acting funny,
> UPDATE tblEmpPersonalInfo SET
> SepDate = EmpSWVTCSepDate
> This query will not successfully run, giving me this error,
> The conversion of a char data type to a datetime data type resulted in an
> out-of-range datetime value.
> The statement has been terminated.
> But, if I edit the query like this,
> UPDATE tblEmpPersonalInfo SET
> SepDate = EmpSWVTCSepDate
> WHERE EmpID = 'aa381234'
> then the query will work fine... I don't want to have to run the query for
> every employee in the database, so how can I do this?
> Thanks,
> Drew
>
>|||Too bad we cannot set some sort of flashing attribute on this message :)
Glad you found your problem, and even more important, glad you are cutting
future problems off at the knee caps. The way a value displays can be dealt
with at runtime, the most important thing is that the value is true!
----
Louis Davidson - drsql@.hotmail.com
SQL Server MVP
Compass Technology Management - www.compass.net
Pro SQL Server 2000 Database Design -
http://www.apress.com/book/bookDisplay.html?bID=266
Note: Please reply to the newsgroups only unless you are interested in
consulting services. All other replies may be ignored :)
"Drew" <drew.laing@.NOswvtc.dmhmrsas.virginia.SPMgov> wrote in message
news:ewv0xWlAFHA.1388@.TK2MSFTNGP09.phx.gbl...
> Thanks... There was 1 invalid date in there, 10-10--2003
> Drew
> "Mike Epprecht (SQL MVP)" <mike@.epprecht.net> wrote in message
> news:u4k2MPlAFHA.2604@.TK2MSFTNGP10.phx.gbl...
>
date formatting
hi
below is my query AdditionalField3 is varchar datatype .and in this field my date is
storing like this 12/05/06..now i wanted to change format of this field AdditionalField3
like 2006-12-5
how to do this?
SELECT *
FROM Tbl_CMS_UploadDetails
WHERE AdditionalField3 = '2006-12-5'
You can use the following statement..
SELECT *
FROM Tbl_CMS_UploadDetails
WHERE Cast(AdditionalField3 as datetime) = Cast('2006-12-5' as datetime)
i m getting below error
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
|||Ok.. What is your date format 12/05/06|||yes and that field is varchar|||Ok..
If you use dd/mm/yy
SELECT *
FROM Tbl_CMS_UploadDetails
WHERE Convert(datetime, AdditionalField3, 103) = Cast('2006-12-5' as datetime)
if you use mm/dd/yy
SELECT *
FROM Tbl_CMS_UploadDetails
WHERE Convert(datetime, AdditionalField3, 101) = Cast('2006-12-5' as datetime)
i tried both queries getting error
Server: Msg 241, Level 16, State 1, Line 1
Syntax error converting datetime from character string.
yes this field also containing bank name ...we r using this field as common field so here for some cases we storing name and for other date thats why this field is varchar type ..for this purpose we r using format_id..
like this
for 83 we r storing date ..
SELECT *
FROM Tbl_CMS_UploadDetails
WHERE Convert(datetime, AdditionalField3, 101) = Cast('2006-12-5' as datetime) and format_id=83
use the following query..
|||
Code Snippet
--If you use dd/mm/yy
SET DATEFORMAT dmy
SELECT *
FROM Tbl_CMS_UploadDetails
WHERE Case When Isdate(AdditionalField3)=1 Then Convert(datetime, AdditionalField3, 103) Else NULL END = Cast('2006-12-5' as datetime)
--if you use mm/dd/yy
SET DATEFORMAT mdy
SELECT *
FROM Tbl_CMS_UploadDetails
WHERE Case When Isdate(AdditionalField3)=1 Then Convert(datetime, AdditionalField3, 101) Else NULL END = Cast('2006-12-5' as datetime)
getting error
Server: Msg 156, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'Then'.
again error
Server: Msg 241, Level 16, State 1, Line 3
Syntax error converting datetime from character string.
Date Formats/Styles
e.g Convert(Varchar(11),GetDate(),106)
I cant find these style codes or this method documented in BOL.
I want to format a date like this: 09 August 2005. How?
Thanks.
hals_leftBetter to do the formating in the client side.
CAST and CONVERT
http://msdn.microsoft.com/library/d...br />
2f3o.asp
AMB
"hals_left" wrote:
> Hi, Is there any list available of style codes used in formatting dates
> e.g Convert(Varchar(11),GetDate(),106)
> I cant find these style codes or this method documented in BOL.
> I want to format a date like this: 09 August 2005. How?
> Thanks.
> hals_left
>|||Did you look up CONVERT in BOL? But there is not a format like that
available. You could write a pretty easy function to return the data like
that using DATEPART and DATENAME, but unless you really have to use SQL, as
Alejandro said, use the client to change the appearance of the data.
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"hals_left" <cc900630@.ntu.ac.uk> wrote in message
news:1123616217.059593.295580@.g44g2000cwa.googlegroups.com...
> Hi, Is there any list available of style codes used in formatting dates
> e.g Convert(Varchar(11),GetDate(),106)
> I cant find these style codes or this method documented in BOL.
> I want to format a date like this: 09 August 2005. How?
> Thanks.
> hals_left
>
Thursday, March 8, 2012
date format, select convert(varchar(8), getdate(), 1)
With this clause "select convert(varchar(16), getdate(), 101)" I can get mmddyyyy but
How can I get time such as mmddyyyyhhmm
Thanks
Daniel
I do not believe there is a standard format that will give you exactly what you are wanting. Here is how to do it using DATEPART and REPLICATE to pad the items out.
Code Snippet
SELECT REPLICATE('0', 2-LEN(DATEPART(mm, getdate()))) + CAST(DATEPART(mm, getdate()) AS VARCHAR(2)) + REPLICATE('0', 2-LEN(DATEPART(dd, getdate()))) + CAST(DATEPART(dd, getdate()) AS VARCHAR(2)) + CAST(DATEPART(YY, getdate()) AS VARCHAR(4)) + REPLICATE('0', 2-LEN(DATEPART(hh, getdate()))) + CAST(DATEPART(hh, getdate()) AS VARCHAR(2)) + REPLICATE('0', 2-LEN(DATEPART(mi, getdate()))) + CAST(DATEPART(mi, getdate()) AS VARCHAR(2)) |||select convert(varchar(16), getdate(), 101)+LEFT(REPLACE(convert(varchar, getdate(), 108), ':', ''),4)
This will get the format of hh:mms (108) and you just replace the : with nothing and take the last 2 characters off.
Very good
I have mmddyyyyhhmm but a little error
I get 04/19/20071223
should be 04/19/2007 12:23
Thanks
Daniel
Code Snippet
create function dbo.fn_FormatADate(
@.dtInput datetime
)
returns char(13)
as
begin
return replace(Replace( convert(varchar,@.dtInput,101) + left(convert(varchar,@.dtInput,108),5) ,'/',''),':','')
end
GO
select dbo.fn_FormatADate(getdate())
GO
|||select convert(varchar(16), getdate(), 101)+' '+LEFT(convert(varchar, getdate(), 108),5)
That should give you the format that you illustrated in your "should be".
|||
Hi Ben,
Glad to see you here.
Regards,
Alejandro Mesa
|||Just a thought...since we always know the len of the output, replicate is a bit more combersome than using "RIGHT"...
Code Block
declare @.TheDate datetime
set @.TheDate = GetDate()
select
right('0' + convert(varchar,datepart(Month,@.TheDate)), 2) --The Month
+ right('0' + convert(varchar,datepart(Day,@.TheDate)), 2) --The Day
+ convert(varchar,datepart(Year,@.TheDate)) --For the Year
+ right('0' + convert(varchar,datepart(hour,@.TheDate)), 2) --The hour
+ right('0' + convert(varchar,datepart(minute,@.TheDate)), 2) --The minute
date format problem
HI
i AM GETTING PROBLEM WITH DATE FROMATS.
i have one query like this
select S.Trid,S.Dept,convert(varchar,S.Submittedon,107) as Submittedon,S.Subbyempno,S.Reqcurrently,
S.ManagersName,case S.Diffcost when '' then 'No' else 'Yes' end as Diffcostcenter,S.Status,S.Airline,
convert(varchar,S.Actionon,107) as Actionon,S.Actionby,S.reqemail,S.onbehalfof from status as S
where (S.Actionon=Convert(varchar,'5 Mar 2007',107))order by S.Submittedon
Actually here s.actionon=convert(varchar,'5 mar 2007',107)) here i am passing text control value taking from calender control
S.Actionon=Convert(varchar,'"+txtControl.Text.ToString()+"',107))";
this txtcontrol value is '5 Mar 2007'.
according to my table actionon field format is Mar 05, 2007.
When i m changing my query to this date format,it retreiving value.
But my query is generated dynamically based on selected value from control.
i want to change txtcontrol value to Mar 05,2007 format.
How to do this one.?
Thanks.
Hi,
You can use following
Convert.ToDateTime(txtControl.Text, 'mmm dd, yyyy');
And, you do not need to call method txtControl.Text.ToString() because Text property itself is a string type.
Thanks,
|||Hi
I am getting error like
"Incorrect syntax near '.'."
When i used what u said.
Some syntax problem is there but I am not getting that problem.
Please help me.
Thanks.
Hi,
Please try following :
public string FormatDate(string strDate) {try { Convert.ToDateTime("02/07/2007").ToString("MMM, dd yyyy"); }catch (Exception ex) {throw new Exception("Invalid string to format as date!!"); } } Hope this works!!|||Hi,
Please try following :
public string FormatDate(string strDate) {string result =string.Empty;try { result = Convert.ToDateTime("02/07/2007").ToString("MMM, dd yyyy"); }catch (FormatException) {throw new Exception("Invalid string to format as date!!"); }return result; }
Hope this works!!
Date Format MM/YYYY
I need to format a date like this:
01/2004 -> 'MM/YYYY'
I know that I can do this...
SELECT CAST(datepart(mm,getdate()) AS VARCHAR) + '/' + CAST(datepart(yyyy,getdate()) AS VARCHAR)
but , Is there is another better solution?select right(convert(char(10), getdate(), 103), 7)|||Originally posted by joejcheng
select right(convert(char(10), getdate(), 103), 7)
Thanx a lot :D.
You save my life !!
Saturday, February 25, 2012
Date format
SELECT
convert(datetime,Convert(varchar(10),getdate(),20) ,110) as Dateselect convert(varchar,getdate(),101) ?
Date Format
example, JAN, when CAST as a varchar it becomes 1, NOT 01Use function CONVERT instead.
Example:
select convert(varchar, getdate(), 126)
AMB
"Jim Yurt" wrote:
> How can you maintain consistance in generating output for a DATE datatype?
> example, JAN, when CAST as a varchar it becomes 1, NOT 01|||Can you elaborate a bit more? Are you saying that you want a particular outp
ut string format which
isn't available in the 3:rd parameter to the CONVERT function? Or do you wan
t to convert into a
string format which SQL Server later will be able to convert into datetime s
afely regardless of
language settings?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
http://www.sqlug.se/
"Jim Yurt" <jyurt@.odh.oh.gov> wrote in message
news:A2EF5257-1A59-4C55-ADAD-2EAE71CB6ED8@.microsoft.com...
> How can you maintain consistance in generating output for a DATE datatype?
> example, JAN, when CAST as a varchar it becomes 1, NOT 01|||if I do something like this;
ELSE(Month(Convert(varchar, DATEFIELD, 126)))
for months up to October (10th) month, my output is 1 char wide, I would
like the 0 as a place holder, so to speak...
jan = 01 NOT 1
feb = 02 NOT 2...
need fixed format for output
"Tibor Karaszi" wrote:
> Can you elaborate a bit more? Are you saying that you want a particular ou
tput string format which
> isn't available in the 3:rd parameter to the CONVERT function? Or do you w
ant to convert into a
> string format which SQL Server later will be able to convert into datetime
safely regardless of
> language settings?
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
> http://www.sqlug.se/
>
> "Jim Yurt" <jyurt@.odh.oh.gov> wrote in message
> news:A2EF5257-1A59-4C55-ADAD-2EAE71CB6ED8@.microsoft.com...
>
>|||> ELSE(Month(Convert(varchar, DATEFIELD, 126)))
Is above the code you are actually executing? Only specifying varchar, witho
ut length, is same as
saying varchar(1), except in CAST and CONVERT where it defaults to 30 (for s
ome strange reason).
Anyhow, always specify the length.
Also, what datatype s DATEFIELD of? Datetime? If so, no need for the CONVERT
function at all.
Your problem is that the Month function returns an integer, not a string. Th
e number 01 and 1 is the
same number. We still don't know what you are doing with the number returned
from the expression. Is
it to be compared to a string in which you have leading zeroes? If so, why d
o you have those numbers
in a string datatype?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
http://www.sqlug.se/
"Jim Yurt" <jyurt@.odh.oh.gov> wrote in message
news:7A4CE644-C87E-443E-8E49-7349038BCF99@.microsoft.com...
> if I do something like this;
> ELSE(Month(Convert(varchar, DATEFIELD, 126)))
> for months up to October (10th) month, my output is 1 char wide, I would
> like the 0 as a place holder, so to speak...
> jan = 01 NOT 1
> feb = 02 NOT 2...
> need fixed format for output
> "Tibor Karaszi" wrote:
>|||DATEFIELD (for the example) is datetime (datatype)...and to your point, MONT
H
return an integer, that's what I don't want.
I need a way to return the CHAR value of the MONTH from a datetime field...
"Tibor Karaszi" wrote:
> Is above the code you are actually executing? Only specifying varchar, wit
hout length, is same as
> saying varchar(1), except in CAST and CONVERT where it defaults to 30 (for
some strange reason).
> Anyhow, always specify the length.
> Also, what datatype s DATEFIELD of? Datetime? If so, no need for the CONVE
RT function at all.
> Your problem is that the Month function returns an integer, not a string.
The number 01 and 1 is the
> same number. We still don't know what you are doing with the number return
ed from the expression. Is
> it to be compared to a string in which you have leading zeroes? If so, why
do you have those numbers
> in a string datatype?
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
> http://www.sqlug.se/
>
> "Jim Yurt" <jyurt@.odh.oh.gov> wrote in message
> news:7A4CE644-C87E-443E-8E49-7349038BCF99@.microsoft.com...
>
>|||Allow me to rephrase your requirement - return the month of a datetime value
as a char(2) value with leading zeros. When you phrase it that way (and
when it exactly defines what you want), the solution becomes much easier to
find.
select convert(char(2), getdate(), 101)
"Jim Yurt" <jyurt@.odh.oh.gov> wrote in message
news:2159CCA0-3841-4436-8356-782E18E28821@.microsoft.com...
> DATEFIELD (for the example) is datetime (datatype)...and to your point,
MONTH
> return an integer, that's what I don't want.
> I need a way to return the CHAR value of the MONTH from a datetime
field...
> "Tibor Karaszi" wrote:
>
without length, is same as
(for some strange reason).
CONVERT function at all.
string. The number 01 and 1 is the
returned from the expression. Is
why do you have those numbers
would
particular output string format
you want to convert into a
datetime safely regardless of
datatype?|||Thanks for making more sense of my 'query'...
indeed what I was looking for was something like this;
convert(char(2), DATEFIELD, 101) + convert(char(2), DATEFIELD, 103) +
convert(char(4), DATEFILED, 126)
which was much better than this;
replace(replace(substring(convert(varcha
r(15), DATEFIELD, 126),5,3) +
substring(convert(varchar(15), DATEFIELD, 126),9,3) +
substring(convert(varchar(15), DATEFIELD, 126),1,4), 'T', ''), '-', '')
thanks for the help everyone!
"Scott Morris" wrote:
> Allow me to rephrase your requirement - return the month of a datetime val
ue
> as a char(2) value with leading zeros. When you phrase it that way (and
> when it exactly defines what you want), the solution becomes much easier t
o
> find.
> select convert(char(2), getdate(), 101)
> "Jim Yurt" <jyurt@.odh.oh.gov> wrote in message
> news:2159CCA0-3841-4436-8356-782E18E28821@.microsoft.com...
> MONTH
> field...
> without length, is same as
> (for some strange reason).
> CONVERT function at all.
> string. The number 01 and 1 is the
> returned from the expression. Is
> why do you have those numbers
> would
> particular output string format
> you want to convert into a
> datetime safely regardless of
> datatype?
>
>|||You will get same result with:
select replace(convert(varchar(10), DATEFIELD, 101), '/', '')
go
AMB
"Jim Yurt" wrote:
> Thanks for making more sense of my 'query'...
> indeed what I was looking for was something like this;
>
> convert(char(2), DATEFIELD, 101) + convert(char(2), DATEFIELD, 103) +
> convert(char(4), DATEFILED, 126)
> which was much better than this;
>
> replace(replace(substring(convert(varcha
r(15), DATEFIELD, 126),5,3) +
> substring(convert(varchar(15), DATEFIELD, 126),9,3) +
> substring(convert(varchar(15), DATEFIELD, 126),1,4), 'T', ''), '-', '')
> thanks for the help everyone!
> "Scott Morris" wrote:
>|||And a last comment - formatting of datetime values is best done on the
client (where language/regional issues are more appropriately handled).
"Alejandro Mesa" <AlejandroMesa@.discussions.microsoft.com> wrote in message
news:01094609-D7E9-4C70-9AB6-A2DB89157AE5@.microsoft.com...
> You will get same result with:
> select replace(convert(varchar(10), DATEFIELD, 101), '/', '')
> go
>
> AMB
> "Jim Yurt" wrote:
>
value
(and
easier to
point,
varchar,
30
the
number
so,
I
Or do
into
DATE
Sunday, February 19, 2012
Date Conversion in SQL Server
Here are the fields I have
eventDate = smallDateTime 2005-12-12 00:00:00
eventTime = varchar(20) 1:00:00
newEventDate = dateTime [desired result: 2005-12-12 1:00:00]
When I run the following script:
update healthEvent
set newEventDate = cast(substring(convert(varchar,eventDate,120),1,10 )+' '+eventTime as DateTime)
I get "Syntax error converting datetime from character string." error.
Any ideas why?
Thanks!
-Parul-- Comment
What in the name of all that is relational and logical would somebody design a POS like this?
-- Answer
Because you are not putting them together properly.
The date string at 1 AM is like this:
2007-05-17 01:00:00.000
The date string at 1 PM is like this:
2007-05-17 13:00:00.000
You are trying to slam the 1 against the space after the date without the leading zero.
Start from the inside and work out. When I convert, I like to explicitly define the size of my char variable inside of the convert instead of letting a varchar guess at what i want (convert(char(10),eventDate,120).
In this case I would use an 11 char convert to pick up the space after the date portion plus a 0 plus the ltrim(rtrim(time)) component.
declare @.eventDate smallDateTime
select @.eventDate = '2005-12-12 00:00:00'
declare @.eventTime varchar(20)
select @.eventTime = '1:00:00'
declare @.newEventDate dateTime --[desired result: 2005-12-12 1:00:00]
set @.newEventDate = cast(substring(convert(varchar,@.eventDate,120),1,1 0 )+' 0'+@.eventTime as DateTime)
select @.newEventDate
-- Results
----------------
2005-12-12 01:00:00.000
(1 row(s) affected)|||Thanks so much for your reply.
Unfortunatley, I am still getting the same error as I try to insert @.newEventDate into another date field.|||Plus do I need that leading zero at all times? What if I have @.eventTime as '11:00:00'|||You will have to do a CASE statement for your time segment on the datalength of the ltrim(rtrim(time segment)) . If len = 5 add the zero else don't.
Friday, February 17, 2012
Date Conversion
a varchar type field. I am trying to Insert it into another table that has
a DateTime type field. I have tried Convert and Cast. I am not sure if I
can even do this! Any ideas?
The code that I have is
Insert Into MasterJobLog
(RSID,
Code,
DateStamp,
DocumentName,
Pages,
Cost,
Client,
PatronID,
Printer,
DocumentType )
Select 'RS101', Code, DateStamp,
DocumentName,Pages,Cost,Client,PatronID,Printer,DocumentType from RS101
Thanks
ArthurNot very pleasant, but it works, perhaps someone else will come up with a
slicker way...
create table test( a varchar(100) not null)
go
insert into test values ('09042003143404')
GO
select convert(datetime,substring(a,5,4) + substring(a,1,2)
+ substring(a,3,2) + ' ' + substring(a,9,2) + ':'
+ substring(a,11,2) + ':' + substring(a,13,2)) from test
Wayne Snyder, MCDBA, SQL Server MVP
Computer Education Services Corporation (CESC), Charlotte, NC
www.computeredservices.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
"Arthur C" <arthur.christy@.tamut.edu.delete.me> wrote in message
news:#bCqoVzlDHA.2268@.TK2MSFTNGP12.phx.gbl...
> I have a table that has '09042003143404' which is Date and Time Combined
in
> a varchar type field. I am trying to Insert it into another table that
has
> a DateTime type field. I have tried Convert and Cast. I am not sure if I
> can even do this! Any ideas?
>
> The code that I have is
> Insert Into MasterJobLog
> (RSID,
> Code,
> DateStamp,
> DocumentName,
> Pages,
> Cost,
> Client,
> PatronID,
> Printer,
> DocumentType )
> Select 'RS101', Code, DateStamp,
> DocumentName,Pages,Cost,Client,PatronID,Printer,DocumentType from RS101
>
> Thanks
> Arthur
>|||> I have a table that has '09042003143404' which is Date and Time Combined
in
> a varchar type field.
Ugh, why?
> I am trying to Insert it into another table that has
> a DateTime type field.
INSERT otherTable(DateTime_Column_Not_Field)
SELECT CONVERT
(
DATETIME,
SUBSTRING(Silly_Varchar_Column_Not_Field, 5, 4)
+ SUBSTRING(Silly_Varchar_Column_Not_Field, 1, 2)
+ SUBSTRING(Silly_Varchar_Column_Not_Field, 3, 2) + ' ' +
+ STUFF(STUFF(RIGHT(Silly_Varchar_Column_Not_Field, 6), 5, 0, ':'), 3,
0, ':')
)
FROM OriginalTable|||hehehhe...lets stuff the turkey...
select cast(stuff(stuff(stuff(stuff(a,13,0,':'),11,0,':'),9,0,left(a,4)+'
'),1,4,'') as datetime) dt
from test
--
-oj
Rac v2.2 & QALite!
http://www.rac4sql.net
"Wayne Snyder" <wsnyder@.computeredservices.com> wrote in message
news:%23A%23r41zlDHA.3256@.tk2msftngp13.phx.gbl...
> Not very pleasant, but it works, perhaps someone else will come up with a
> slicker way...
> create table test( a varchar(100) not null)
> go
> insert into test values ('09042003143404')
> GO
> select convert(datetime,substring(a,5,4) + substring(a,1,2)
> + substring(a,3,2) + ' ' + substring(a,9,2) + ':'
> + substring(a,11,2) + ':' + substring(a,13,2)) from test
>
> --
> Wayne Snyder, MCDBA, SQL Server MVP
> Computer Education Services Corporation (CESC), Charlotte, NC
> www.computeredservices.com
> (Please respond only to the newsgroups.)
> I support the Professional Association of SQL Server (PASS) and it's
> community of SQL Server professionals.
> www.sqlpass.org
>
> "Arthur C" <arthur.christy@.tamut.edu.delete.me> wrote in message
> news:#bCqoVzlDHA.2268@.TK2MSFTNGP12.phx.gbl...
> > I have a table that has '09042003143404' which is Date and Time Combined
> in
> > a varchar type field. I am trying to Insert it into another table that
> has
> > a DateTime type field. I have tried Convert and Cast. I am not sure if
I
> > can even do this! Any ideas?
> >
> >
> >
> > The code that I have is
> > Insert Into MasterJobLog
> > (RSID,
> > Code,
> > DateStamp,
> > DocumentName,
> > Pages,
> > Cost,
> > Client,
> > PatronID,
> > Printer,
> > DocumentType )
> > Select 'RS101', Code, DateStamp,
> > DocumentName,Pages,Cost,Client,PatronID,Printer,DocumentType from RS101
> >
> >
> > Thanks
> > Arthur
> >
> >
>|||That works. Thanks
"Arthur C" <arthur.christy@.tamut.edu.delete.me> wrote in message
news:%23bCqoVzlDHA.2268@.TK2MSFTNGP12.phx.gbl...
> I have a table that has '09042003143404' which is Date and Time Combined
in
> a varchar type field. I am trying to Insert it into another table that
has
> a DateTime type field. I have tried Convert and Cast. I am not sure if I
> can even do this! Any ideas?
>
> The code that I have is
> Insert Into MasterJobLog
> (RSID,
> Code,
> DateStamp,
> DocumentName,
> Pages,
> Cost,
> Client,
> PatronID,
> Printer,
> DocumentType )
> Select 'RS101', Code, DateStamp,
> DocumentName,Pages,Cost,Client,PatronID,Printer,DocumentType from RS101
>
> Thanks
> Arthur
>
Date Comparison
Example: '2005-12-27 00:00:00.000'
The other table is defined as datetime, and it does have the date and time in this field.
Example: 2005-12-27 08:00:35.000
The problem i am having is
2005-12-27 00:00:00.000 does not = 2005-12-27 08:00:35.000.
Because I will never have more than one record on the same date I would like to be able to only compare the date. Example 2005-12-27 = 2005-12-27
Since the fields are 2 different field types, this is giving me a problem. Could someone please help. I have tried everything I know to do.
What I really need is the a way to format the datetime fields date into a string such as '2005-12-27'.
Hopefully what i have written makes sense.
Thanksselect cast(convert(varchar(11),getdate()) as Datetime)
this eliminates the time stamp and sets it to 2006-05-27 00:00:00.000
This will allow you to join
Suggestion make your varchar field a date field.|||Or,Use the below code to convert date to varchar and compare with ur varchar field
select convert(varchar,DATEADD(dd, DATEDIFF(dd,0,getdate()), 0),121)|||That worked perfect! Thanks!