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.
Hi, I'm having trouble updating a DateTime field in my SQL database. Here is what I'm trying to do....I retrieve the existing value in the DateTime field (usually a bum date like 1/1/1900 00:00:00:00), then put it in a variable. Later, depending on some conditions, I'll either update the DateTime field to today's date (which works great) or set it back equal to the existing value from the variable (this one messes up and says "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM. "). There is a ton more than this but here are the relevant snippets:<code>Dim CompDate As DateTimeDim aComm As SQLCommand Dim aReader As SQLDataReader Dim bSQL,bConn As String bSQL= "SELECT CompleteDate,StatusOfMarkout FROM Tickets WHERE TicketName=" _ & CHR(39) & Trim(Ticket.Text) & CHR(39) bConn = serverStuff aConn = New SQLConnection(bConn) aComm = New SQLCommand(bSQL,aConn) aConn.Open() result = aComm.ExecuteReader() 'fills controls with data While result.Read() CompDate = result("CompleteDate") PreviousMarkoutStatus.Text = result("StatusOfMarkout") End While result.Close() aConn.Close()sSqlCmd ="Update OneCallTickets CompleteDate=@CompleteDate, StatusOfMarkout=@StatusOfMarkout WHERE TicketFileName=@TicketFileName" dim SqlCon as New SqlConnection(serverStuff) dim SqlCmd as new SqlCommand(sSqlCmd, SqlCon) If Flag1List.SelectedItem.Value = "No Change" Then SqlCmd.Parameters.Add(new SqlParameter("@Flag1", SqlDbType.NVarChar,35)) SqlCmd.Parameters("@Flag1").Value = PreviousMarkoutStatus.Text SqlCmd.Parameters.Add(new SqlParameter("@CompleteDate", SqlDbType.DateTime, 8)) SqlCmd.Parameters("@CompleteDate").Value = CompDateElse SqlCmd.Parameters.Add(new SqlParameter("@Flag1", SqlDbType.NVarChar,35)) SqlCmd.Parameters("@Flag1").Value = CurrentStatus.Text SqlCmd.Parameters.Add(new SqlParameter("@CompleteDate", SqlDbType.DateTime, 8)) SqlCmd.Parameters("@CompleteDate").Value = Today()End IfSqlCon.Open() SqlCmd.ExecuteNonQuery() SqlCon.Close()</code>Can anybody help me with this? Thanks a bunch
I want to write some SQL which results in an automatic conversion of adatetime to a string in a format suitable for the Language of theconnection (either by explicitly setting the Language in theconnection string, or by setting the default language in for the userused for the connection.)The casting from string to datetime uses the language setting:Data Source=localhostsqlexpress;Initial Catalog=master;PersistSecurity Info=True; Language =BRITISH ENGLISH; Trusted_Connection=yes;Application Name = Test Application;select cast('13/01/2008' as datetime) --WORKS as expectedselect cast('01/13/2008' as datetime) --FAILS as expectedandData Source=localhostsqlexpress;Initial Catalog=master;PersistSecurity Info=True; Language =ENGLISH; Trusted_Connection=yes;Application Name = Test Application;select cast('13/01/2008' as datetime) --FAILS as expectedselect cast('01/13/2008' as datetime) --WORKS as expectedbut implicit casting the other way ignores the "Language setting" (iethe format is the same for both):BRITISH ENGLISHselect cast(cast('12/01/2008' as datetime) as nvarchar(max)) --Jan 122008 12:00AMselect convert(nvarchar(max),cast('12/01/2008' as datetime)) --Jan 122008 12:00AMENGLISHselect cast(cast('12/01/2008' as datetime) as nvarchar(max)) --Dec 12008 12:00AMselect convert(nvarchar(max),cast('12/01/2008' as datetime)) -- Dec 12008 12:00AMIs it possible to tell SQL Server "For language w convert datetimes tostrings using format x, but for language y use format z?"Regards,Dan
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
Hi,I'm creating a database using SQL Server 2005 Express Edition (Comes with Visual Web Developer). The table which I am creating has the following Fields - all don't allow nulls:IDUserIdDateDescription(UserId is a foreign key to asp_net_Users as I am supporting user accounts)Basically what I need to do is create a page where I as an Administrator can log onto and enter just the text for the field Description. Then once I upload this I wish all users to visit the site and view this Description on a page however with it also listing the Administrator who wrote it along with the Date. I wish both of these fields to be added automatically (UserId to display the User Name and the Date to display the date and time with which the Description was added - However these need to be editable by the Administrator if he/she wishes to change them).Can anyone point me in the right direction on the steps needed to create this scenario?Thanks for any helpDaniel
Hi, I have a question regarding inserting numbers automatically. For example, there are 2 fields. One is CountryID and other is CountryName. From Front-end I'm entering the Country Name "India" alone and in my table the CountryID "1" or what ever the sequence should be entered. I believe this can be done using Triggers. I read on KB article in Microsoft website. But didn't get clear idea. Is that the correct way?Can any one show me a small example of this? Or give an idea for this?
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
i have a student table and i created a stored procedure to insert a new student in this table but student_id field wich i put it as primary key got error because allready record has same value .how i can know the last row's student_id value and input a new valid value in one stored procedure thanks
I am trying to drag data from Informix to Sql Server. When I kick off the package using an OLE DB Source and a SQL Server Destination, I get DT_DBDATE to DT_DBTIMESTAMP errors on two fields from Informix which are date data ....no timestamp part
I tried a couple of things:
Created a view of the Informix table where I cast the date fields as datetime year to fraction(5), which failed.
Altered the view to convert the date fields to char(10) with the hopes that SQL Server would implicitly cast them as datetime but it failed.
I am designing a database. I want to define a automatic sequence on a table primary key field. what is the best solution for it?
I know I can enable identity property for a field, but it has some problems ( for example its seed jumps on restart and unsuccessful events)
I also can use some calculated sequences. for example I can calculate max of the filed values and after incrementing use it as key for new inserted record.
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?
below is the query that is a part of a sproc .All table fields and values are ok. When the mentioned Sproc. is called in query analyzer it executes well and update all fields of the table used in UPDATE statement . UPDATE Emp_Schedule SET IOS = 0, HoursWorked = @WorkTime, COA =getdate() WHERE (Emp_Id = @EmpID) AND (S_Id = @ShiftId) AND (DT =@DayTime)
PROBLEM arises when i call this procedure from C# code all fields are updated Except the COA(DateTime) field.Whats the problem. SProc runs well both in debug mode and normal mode in query analyzer and do updates the values. But when i call in C# only datetime field COA is not Updated? Plz solve this. THNX IN Advance.
Hi People, hope someone can help me out here with a little problem. Basically i've go a asp.net page which has a listbox on. This list box is populated from a SQL database table with the datetime of the a selected field. Thus in the list box you get a list of strings looking like this "24/09/07 12:58" Also on the page is a submit button, and some other editing textboxes. The main issue here is the when the submit button is used i get the currently selected listbox timedate string and then pass this along with other items to update a record in the database based on the datetime in the listbox control.
Below is how i get the string from the listbox control Dim except_time As DateTime except_time = DropDownList1.SelectedValue The expect_time is then passed to store procedure along with some other vars, which looks like this -- =============================================-- Author: Lee Trueman-- Create date: 1st Sept 2007-- =============================================CREATE PROCEDURE [dbo].[spExcept_UpdateData] -- Add the parameters for the stored procedure here @validated bit, @update_time datetime, @except_time datetimeASBEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON -- Insert statements for procedure here UPDATE exceptions SET validated = @validated, update_time = @update_time WHERE (except_time = @except_time)END So validated and update_time should be updated when except_time is equal to @except_time
My problem is that the database never updates. If i debug the asp.net page the watch var shows the datetime in US format (I.e "09/24/07 12:58"), if this is true then this would explain why when it is passed to the stored proc nothing gets updated, as there would not be a date match. can anyone see any silly mistakes i'm doing here ????
I need to set only the date part of tblEventStaffRequired.StartTime to tblEvents.EventDate while maintaining the time part in tblEventStaffRequired.StartTime.
UPDATE tblEventStaffRequired SET StartTime = <expression here> FROM tblEvents INNER JOIN tblEventStaffRequired ON tblEvents.ID = tblEventStaffRequired.EventID
I have a table with a datetime field 'TheDate'. Currently dates are stored as 'mm-dd-yyyy 00:00:00'. Is there a way to get just the month, day and year parts, '01/01/2008' into the field without changing the field data type to varchar? I'm asking because when I do this:
update TheTable set TheDate = substring(convert(varchar,TheDate,101),1,10)
I'm still getting a date in the format 'mm-dd-yyyy 00:00:00' stored in the table. I'd like to be able to lose the time portion, but I'd like to be able to keep the datetime datatype for date math purposes. Can it be done?
Hi, I want to update a field in my table whose value is a 0, to a value 1. This field is of type bit and here is the SP that I wrote to achieve this. Somhow, its giving some error when I tried executing it in the Query Analyzer. What am I doing wrong here??
CREATE PROCEDURE PublishSchedule ( @SiteCode smallint, @YearMonth int ) AS
DECLARE @Active bit IF ( (SELECT COUNT(*) FROM CabsSchedule WHERE YearMonth = @YearMonth AND SiteCode = @SiteCode) > 0 ) BEGIN UPDATE CabsSchedule SET Active=1 WHERE SiteCode=@SiteCode AND YearMonth=@YearMonth END GO
All other fields are updating ok and I'm not getting an error.I am trying to update a date and time (smalldatetime) using a stored procedure.First, the info to be updated comes from a datagrid. Dim sDate As DateTime sDate = CType(e.Item.FindControl("tDate"), TextBox).TextThen, passed to the SQLDal class and then to the stored procedure..... Public Function updateData(ByVal sDate As DateTime, ByVal sp As String) 'Some items snipped for easier read Dim command As SqlCommand = New SqlCommand(sp, conn) 'Where sp is the stored procdure name command.Parameters.Add("@date", sDate)'And so on.....And then the stored procedure....@num VARCHAR(256),@date SMALLDATETIME,@contact VARCHAR(256),@notes VARCHAR(8000),@media VARCHAR(256) ASBEGIN DECLARE @errCode INT BEGIN TRAN -- UPDATE THE RECORDS UPDATE dbo.tblData SET fldDate = @date, fldContact = @contact, fldNotes = @notes, fldMedia = @media WHERE fldNum = @num <sniped>Like I said, all other fields are updated with no problems, but not the date.The date format being passed into the sp is {0:MMM dd, yyyy hh:mm tt} or Aug 05, 2005 04:39 PM Is it the format of the date? Or something else I'm not seeing...Thanks all,Zath
I have a sql database that includes a table of customer contact information. The area code for many of my customers is about to change. Is there a way to mass update the phone number field so that all phone numbers that currently start with 111 change to 222 ? Ex 1115554444 to 2225554444 ?
I try to update a field of text datatype using WRITETEXT statement. The information that I try to change has both the single(') and double (") quotes in it. How can I get it done ?
Trying to update part of a field. Currently using ColdFusion 4.0 and SQL Server 7.0. My field looks something like this: ABC.DEF.GHI and I just want to update the last 3 characters, GHI. The length of the field may change so it's not going to be 11 characters long. Any help would be appreciated.
I have 3 tables and 1 view. Which are: TOWNLAND_GEOREFERENCE_POLYGON PlanningPointLocation paflarea VIEW_paapplic
The View paaplic has 100 records and I have to do the below for all 1000 records individually. I have to update the field TP_Total in the TOWNLAND_GEOREFERENCE_POLYGON table depending on what is in the fields in the tables. I am writing the below code but am unsure if this is going to achieve what I want.
BEGIN Select file_number, land_use_code, pluse1_code From VIEW_paapplic END
BEGIN If pluse1_code = 'A' Then Select TP_Total From TOWNLAND_GEOREFERENCE_POLYGON WHERE PlanningPointLocations.Townland = TOWNLAND_GEOREFERENCE_POLYGON.Townland AND PlanningPointLocations.File_Number = File_Number
Update TOWNLAND_GEOREFERENCE_POLYGON SET TP_Total As TP_Total + 1 WHERE PlanningPointLocations.Townland = TOWNLAND_GEOREFERENCE_POLYGON.Townland AND PlanningPointLocations.File_Number = File_Number
Else If pluse1_code = 'C' Then Select Count(*) As TempCount From table paflarea Where fk_paapplicfile_nu = file_number
Select TP_Total From TOWNLAND_GEOREFERENCE_POLYGON WHERE PlanningPointLocations.Townland = TOWNLAND_GEOREFERENCE_POLYGON.Townland AND PlanningPointLocations.File_Number = File_Number
Update TOWNLAND_GEOREFERENCE_POLYGON SET TP_Total As TP_Total + TempCount WHERE PlanningPointLocations.Townland = TOWNLAND_GEOREFERENCE_POLYGON.Townland AND PlanningPointLocations.File_Number = File_Number END
ok, i am trying to update a database at work for a product we are developing.
i need to run this command update <tablenamehere> set value = Replace(value, 'GeoLynxAO_Henrico', 'GeoLynx') on every tabe in the database
is there a simple way to do this while pulling the table names out of information_schema.tables?
i have searched using google and been unable to find anything so far. the db server is running sql server express 2005 and i'm doing this from sql server management studio express
i really don't want to have to type the update statement by hand for 90+ tables................
Hi - Once again I've been looking at this forever and not able to see the problem. Have a grid table everything updates except the training date field. That get's wiped out each time - no matter if something is in it or not. Everything else updates correctly. Here's the code: <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="ds1" DataKeyNames="eventID"><Columns><asp:CommandField ButtonType="Button" ShowEditButton="True" ShowDeleteButton="True" /><asp:BoundField DataField="eventID" HeaderText="ID" SortExpression="eventID" ReadOnly="True"><HeaderStyle Font-Bold="True" Font-Names="Verdana" Font-Size="Small" /><ItemStyle Font-Names="Verdana" Font-Size="Small" /></asp:BoundField><asp:TemplateField HeaderText="Training Date" SortExpression="trainingDate"><EditItemTemplate><asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("trainingDate", "{0:M/dd/yy}") %>'></asp:TextBox></EditItemTemplate><ItemTemplate><asp:Label ID="Label1" runat="server" Text='<%# Bind("trainingDate", "{0:M/dd/yy}") %>'></asp:Label></ItemTemplate><HeaderStyle Font-Bold="True" Font-Names="Verdana" Font-Size="Small" /><ItemStyle Font-Names="Verdana" Font-Size="Small" /></asp:TemplateField> <asp:SqlDataSource ID="ds1" runat="server" ConnectionString="<%$ ConnectionStrings:TrainingClassTrackingConnectionString %>" ProviderName="<%$ ConnectionStrings:TrainingClassTrackingConnectionString.ProviderName %>"UpdateCommand="UPDATE [trainingLog] SET [trainingDate] = @trainingDate WHERE [eventID] = ?" > <UpdateParameters><asp:Parameter Name="trainingDate" Type="DateTime" /></UpdateParameters>