DateTime Automatic Formatting
Mar 12, 2008
I want to write some SQL which results in an automatic conversion of a
datetime to a string in a format suitable for the Language of the
connection (either by explicitly setting the Language in the
connection string, or by setting the default language in for the user
used for the connection.)
The casting from string to datetime uses the language setting:
Data Source=localhostsqlexpress;Initial Catalog=master;Persist
Security Info=True; Language =BRITISH ENGLISH; Trusted_Connection=yes;
Application Name = Test Application;
select cast('13/01/2008' as datetime) --WORKS as expected
select cast('01/13/2008' as datetime) --FAILS as expected
and
Data Source=localhostsqlexpress;Initial Catalog=master;Persist
Security Info=True; Language =ENGLISH; Trusted_Connection=yes;
Application Name = Test Application;
select cast('13/01/2008' as datetime) --FAILS as expected
select cast('01/13/2008' as datetime) --WORKS as expected
but implicit casting the other way ignores the "Language setting" (ie
the format is the same for both):
BRITISH ENGLISH
select cast(cast('12/01/2008' as datetime) as nvarchar(max)) --Jan 12
2008 12:00AM
select convert(nvarchar(max),cast('12/01/2008' as datetime)) --Jan 12
2008 12:00AM
ENGLISH
select cast(cast('12/01/2008' as datetime) as nvarchar(max)) --Dec 1
2008 12:00AM
select convert(nvarchar(max),cast('12/01/2008' as datetime)) -- Dec 1
2008 12:00AM
Is it possible to tell SQL Server "For language w convert datetimes to
strings using format x, but for language y use format z?"
Regards,
Dan
View 2 Replies
ADVERTISEMENT
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
Jun 15, 2004
I need to automatically update a datetime field for a record to the current time whenever the record is updated.
create table t (
id bigint identity(1,1) not null primary key,
name varchar(50),
value varchar(50),
ts datetime not null default getutcdate()
)
go
insert t (name, value) values ('fred', 'bob')
go
update t set value='robert' where id=1 and name='fred'
go
One option would be to use an instead of update trigger.
create trigger update_t on t
instead of update as
update t set ts=getutcdate(),name=inserted.name, value=inserted.value from t inner join inserted on t.id=inserted.id
go
update t set value='dick' where id=1 and name='fred'
go
Sounds like I've solved my own problem, heh? Well, here's the catch ... you can't know the names of the other columns at the time you write the trigger. I.e. you only know that there is a ts field that needs to be updated internally, otherwise you want the update to do the same thing it would normally do.
Any ideas?
View 1 Replies
View Related
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
Aug 17, 2005
Is there a way of formatting a DateTime datatype, so e.g. "2005-08-17 18:27:16.753" could format to "dd/mm/yy hh:mm"?
View 2 Replies
View Related
Jun 13, 2002
I am selecting a datetime value from a table but I want it to be
in this format: mm/dd/yyyy
This query is as close as I have come:
select char(month(nancyDateSent))+ '/'+ datename(day,nancyDateSent) + '/' + datename(yy,nancyDateSent) from tbloutgoingobms_hold
but is not correct - I get dates that look like this: /11/2002
Please help - there must be an easier way !!!
Thanks in advance,
Nancy
View 1 Replies
View Related
Oct 17, 2007
Hi,
I need to execute some store procedures I have in the SQL editor but I seem to been having problems with the formatting for datetime variables needed for the execution of my code. can anyone please help?
thanks in Advance
exec [usp_CMSTemplateCreateNewTemplate] 0, 0, 'My First Page', '', 0, CAST(10/16/2007,DATETIME), CAST(10/25/2007, DATETIME), 0, @PageTemplateID=0
THE STORED PROCEDURE SAMPLE
ALTER PROCEDURE [dbo].[usp_CMSTemplateCreateNewTemplate]
@SiteID AS INT,
@PageID AS INT,
@Title AS NVARCHAR(50),
@EditHREF AS NVARCHAR(512),
@CreatorID AS INT,
@StartDate AS DATETIME,
@EndDate AS DATETIME,
@Child AS INT,@PageTemplateID AS INT OUTPUT
AS
View 1 Replies
View Related
May 11, 2015
Part of my query is :
SELECT * FROM TableA
WHERE ColumnA >= DATEADD(DAY, - 30, GETDATE())
With the expression at the where clause above, you can pull a rolling 30 days data without having to supply values. Now users of the report want to see it represented like: 2nd April – 1st May
when the report is ran. the requirement is not to use a parameter for the reportKnowing that I have no parameters, how do I reference ">= DATEADD (DAY, - 30, GETDATE())" to reflect the start date and the end date in the report?
View 3 Replies
View Related
Jul 9, 2007
Hi,
I'm inserting a datetime values into sql server 2000 from c#
SQL server table details
Table nameate_test
columnname datatype
No int
date_t DateTime
C# coding
SqlConnection connectionToDatabase = new SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=testdb;Integrated Security=SSPI");
connectionToDatabase.Open();
DataTable dt1 = new DataTable();
dt1.Columns.Add("no",typeof(System.Int16));
dt1.Columns.Add("date_t", typeof(System.DateTime));
DataRow dr = dt1.NewRow();
dr["no"] = 1;
dr["date_t"] = DateTime.Now;
dt1.Rows.Add(dr);
for(int i=0;i<dt1.Rows.Count;i++)
{
string str=dt1.Rows["no"].ToString();
DateTime dt=(DateTime)dt1.Rows["date_t"];
string insertQuery = "insert into date_test values(" + str + ",'" + dt + "')";
SqlCommand cmd = new SqlCommand(insertQuery, connectionToDatabase);
cmd.ExecuteNonQuery();
MessageBox.Show("saved");
}
When I run the above code, data is inserted into the table
The value in the date_t column is 2007-07-09 22:10:11 000.The milliseconds value is always 000 only.I need the millisecond values also in date_t column.
Is there any conversion needed for millisecond values?
thanks,
Mani
View 3 Replies
View Related
Dec 6, 2006
I'm getting error:
String was not recognized as a valid DateTime.
my insert parameter:
<asp:Parameter Name="LastModified" Type="DateTime" DefaultValue= "<%=DateTime.Now.ToString() %>"
my insert command:
InsertCommand="INSERT INTO [Product] ([Enabled], [ProductCode], [ProductName], [ProductAlias], [CarrierId], [DfltPlanId], [DoubleRating], [DoubleRateProductId], [ConnCharges], [StartDate], [EndDate], [Contracted], [BaseProductId], [LastModified], [LastUser]) VALUES (@Enabled, @ProductCode, @ProductName, @ProductAlias, @CarrierId, @DfltPlanId, @DoubleRating, @DoubleRateProductId, @ConnCharges, @StartDate, @EndDate, @Contracted, @BaseProductId, @LastModified, @LastUser)"
LastModified is a datetime field.
Running sql2005
View 1 Replies
View Related
Mar 14, 2007
Hi all, having a little problem with saving dates to sql databaseI've got the CreatedOn field in the table set to datetime type, but every time i try and run it i get an error kicked up 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."I've tried researching it but not been able to find something similar. Heres the code: DateTime createOn = DateTime.Now;string sSQLStatement = "INSERT INTO Index (Name, Description, Creator,CreatedOn) values ('" + name + "','" + description + "','" + userName + "','" + createOn + "')"; Any help would be much appreciated
View 4 Replies
View Related
Mar 17, 2007
Hey :)I'm facing a lot of troubles trying to create a new pause/break-system. Right now i'm building up the query that counts how many records that is inside 2 fields. Let me first show you my table:
ID (int) | stamp_start (Type: DateTime) | stamp_end (Type: DateTime) | Username (varchar)0 | 17-03-07 12:00:00 | 17-03-07 12:30:00 | Hovgaard
The client will enter a start time and a end time and this query should then count how many records that are inside this periode of time.
Example: The client enter starttime: 12:05 and endtime: 12:35.The query shall then return 1 record found. The same thing if the user enters 12:20 and 12:50.My current query looks like this:SELECT COUNT(ID) AS Expr1 FROM table WHERE (start_stamp <= @pausetime_start) AND (end_stamp >= @pausetime_end)But this will only count if I enter the exact same times as the one inside the table.Any ideas how I can figure this out?Thanks for your time so far :)/Jonas Hovgaard - Denmark
View 2 Replies
View Related
May 13, 2006
Hi,
I have a column of type datetime in sqlserver 2000. Whenever I try to insert the date
'31/08/2006 23:28:59'
I get the error "...datetime data type resulted in an out-of-range datetime value"
I've looked everywhere and I can't solve the problem. Please note, I first got this error from an asp.net page and in order to ensure that it wasn't some problem with culture settings I decided to run the query straight in Sql Query Anaylser. The results were the same. What else could it be?
cheers,
Ernest
View 2 Replies
View Related
Mar 11, 2014
I am inserting date and time data into a SQL Server 2012 Express table from an application. The application is providing the date and time as a string data type. Is there a TSQL way to convert the date and time string to an SQL datetime date type? I want to do the conversion, because SQL displays an error due to the
My date and time string from the application looks like : 3/11/2014 12:57:57 PM
View 1 Replies
View Related
Sep 7, 2007
Nothing difficult, I just need a way to generate a new datetime column based on the column [PostedDate], datetime. So basically I want to truncate the time. Thanks a lot.
View 5 Replies
View Related
Jan 17, 2008
e.g.
1st March 2005 12:00:00
is showing as
01/03/2005 00:00:00
instead of
01/03/2005
Why does this happen?
View 4 Replies
View Related
Jun 15, 2004
I have the following SQL:
select convert(datetime,'04-20-' + right(term,4)) as dt,
'Deposit' as type, a.* from
dbo.status_view a
where right(term,4) always returns a string which constitutes a 4 digit year eg '1999','2004',etc.
The SQL above returns
2004-04-20 00:00:00.000 Deposit ...
Which makes me think that it is able to successfully construct the datetime object inline. But then when I try and do:
select * from
(
select convert(datetime,'04-20-' + right(term,4)) as dt,
'Deposit' as type, a.* from
dbo.status_view a
) where dt >= a.submit_date
I get the following error:
Syntax error converting datetime from character string.
Given that it executes the innermost SQL just fine and seems to convert the string to a datetime object, I don't see why subsequently trying to USE that datetime object for something (in this case comparison with submit_date which is a datetime in the table a) should screw it up. Help!!! Thanks...
View 6 Replies
View Related
Jul 20, 2005
Hi,I have a text file that contains a date column. The text file will beimported to database in SQL 2000 server. After to be imported, I wantto convert the date column to date type.For ex. the text file look likeName dateSmith 20003112Jennifer 19991506It would be converted date column to ydm database in SQL 2000 server.In the table it should look like thisName DateSmith 2000.31.12Jennifer 1999.15.06Thanks in advance- Loi -
View 1 Replies
View Related
Nov 5, 2007
Hi,
I am trying to access a date column up to millisecond precession. So I cast date to as follows:
Code BlockCONVERT(varchar(23),CREATE_DATE,121)
I get millisecond part as a result of query but it€™s €œ000€?.
When I try to test the format by using getDate instead of DateTime column I get right milliseconds.
CONVERT(varchar(23),GetDate(),121) --Gives right milliseconds in return
View 4 Replies
View Related
Feb 9, 2008
Hi,
We are working on creating an automatic backup tool for our web application. Our goal is to run a script that "zips" the virtual host/application directory. We have the script to zip the application directory, but is there a way to run a SQL Backup and then zip the output easily? This is where we are struggling.
Any Suggestions are appreciated
Brent
View 1 Replies
View Related
May 1, 2001
I am getting an automatic rollback in a transaction that fails to insert a row, via a trigger, due to a duplicate key. The transaction is automatically rolled back and unless the error correctly handled a 'partial update' occurs. Why in the example below is the transaction automatically rolled back (statements 1 to 3) and is there any way of knowing what errors generate an auto rollback. For example if the duplicate key error occurs on the insert into table B below, and not the triggered update, then no auto rollback occurs.
Begin Tran -- 1
insert into A values ('A1') -- 2 updates OK
insert into B values ('B1') -- 3 updates OK
-- triggers insert into B_Hist -- 4 Fails with Duplicate Key error
insert into C values ('C1') -- 5 updates OK
Commit Tran -- 6 3902 error No corresponding Begin
Thanks.
View 3 Replies
View Related
Jul 14, 2000
Hi all,
I am using the odbc connector to get a local table. I want that table to get populated every night automatically. How can i do that? Also i want to check if any existing record is updated/changed in the dsn database. Any help is highly appreciated.
Thanks,
Jeff.
View 1 Replies
View Related
Jun 6, 2001
I don't know very much about Sql Server and need help.
I have two primary keys called AirlineCode e ID in the same table.
This id is an automatic number. So I don't need to input this value, since
it's created automatic. What I need is this ID be created automatic but
for each new AirlineCode the ID starts as 1 again. For example :
If I put AirlineCode = 220 then ID starts as 1. In another row AirlineCode is
also 220, then ID is 2. But in another row AirlineCode = 500, then this
automatic number come back to 1.
then the rows can be like this :
AirlineCode ID
220 1
220 2
500 1
220 3
300 1
500 2
I think I have to create a script to make this, but I don't kwon how...
Ask someone to help-me
Best Regards
Marcelo
View 1 Replies
View Related
Mar 28, 2001
Dear Friends,
I want to Automatically take Backup at 7:00 p.m cutoff Time.and automatically restore the database..to a temporary database,generate my report and delete the database.
Friends,this backup & restore should not require any user interface..it should me automatic.
Plz can anyone help me out.
Regards
Salim g belim
View 1 Replies
View Related
Jun 23, 2004
I have two sql 2000 server tables one is active and one is terminated (I inherited this db) and I was thinking of having the active table automatically update the terminated table when an employee is terminated. Access is at the front end and in the form of the active table theres a drop down text box that has the employement status(active, terminated, on leave...etc) so when the status turns into terminated i want the acitve table to send those records to the terminated table, ( the data in both tables are not exactly the same). looking into a trigger or stored procedure. This is the first time I've done this so I'm doing some reasearch on how to handle it. Any suggestions
View 14 Replies
View Related
Jun 25, 2004
well as I get further into this project of automatic updates I'm fining more and more barriers. The combo list box which indicates whether the employee is terminated or active might be a problem with sql since you cant create a Row source and a Row source type in a sql table. that combo box exsist in the properties of the form. The Row Source Type is a Value List. Shoot :(
View 4 Replies
View Related
Jul 16, 2006
I'm a SQL Server 7/2000 DBA and manages about 40 servers in different networks. Every morning I check through the Enterprise Manager if all Jobs (backup, maintenance, etc.) have run successfully. This check costs me 1 hour per day.
Because of a reorganization I've got some new college's and lost some college's. My new college's think this is to much work, so it should be automated. They only want the failed jobs to report an error on a website or something like that, and don't want to check 40 servers. I don't agree in this, because I'm affraid I'm going to miss some errors.
How do you do your checks every morning?
Thanks,
Marco
View 2 Replies
View Related
Apr 22, 2008
hi,
i have:
create table tbl_order
(
id int
,price float
,quantity int
,product nvarchar(50)
,date_of_order smalldatetime
,date_of_change smalldatetime
)
insert into tbl_order (id, price, quantity, product, date_of_order) values (1, 23.21, 2, 'A+B', getdate())
insert into tbl_order (id, price, quantity, product, date_of_order) values (2, 22.21, 2, 'A+B+C', getdate())
and i want to make automatic update:
-if new order is made, i want to update field date_of_change with getdate().
i want to put it in a job with some trigger or something that will recognize instant new insert.
thank you in advance,
View 4 Replies
View Related
May 25, 2008
Hi there,
I am testing the db mirroring, making sure it will auto failover. I've stopped the SQL services on my principal and then I looked at the mirror db is says it's restoring. It stayed like that for 10 min before I enabled the mirroring again. Anyone knows why it's not failing over??????
Here's my setup: SQL 2005 Standard, Server 1 Principal, Server 2 Mirror & Witness.
View 4 Replies
View Related
May 17, 2007
I have initiated database backup plan in 2005,occuring every 2 days.backup plan worked for the first 2 schedules,later backup plans is not working.I have checked the time and date setups,its all fine.how to solve.
View 1 Replies
View Related
Feb 11, 2008
CREATE TABLE [dbo].[tblProve](
[ID][varchar](50)NOT NULL,
[tempCountrys][varchar](100) NULL,
CONSTRAINT [PK_tblProve] PRIMARY KEY CLUSTERED
([ID] ASC) WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
I have a table "dbo.tblProve" that have a Primery Key ID of type
varchar(10) and this primary key have a Default value or Binding like this:
([dbo].[fnc_ProveNewID]())
This function "dbo.fnc_ProveNewID()" finds the max(ID) in the same table and creates the next ID.
When I insert a record into the table dbo.tblProve the function creates the new ID automatically (this is the format of the ID '0000000001' or '000000010' etc. ). But when I insert a lot of records from a Select Query it displays this message below:
Msg 2627, Level 14, State 1, Line 2
Violation of PRIMARY KEY constraint 'PK_tblProve'. Cannot insert duplicate key in object 'dbo.tblProve'.
The statement has been terminated.
Is there any way to create a new ID into a table automatically without to be inserted by the user or client?.
View 8 Replies
View Related
Jul 23, 2005
We use SQL 2000 and our database is configured to grow automatically by10%. Currently 96% of our database is used. At what point will thedatabase expand - what is the trigger point?
View 2 Replies
View Related
Nov 15, 2006
Hi,it's possibile to define table fields for automatic Last_Update_Date and forCreation_date using column formula??Thanks !!!
View 2 Replies
View Related