Trouble With Datetime Insert And Update

Apr 7, 2006

I am trying to Insert or Update a record in MSSQL with a datetime variable which is modified using the DateAdd function.

Basically, I have a table of Coupons which need to expire 'x' days in the future. When I use GetDate() for the Issue Date, I have no problems. But then, when I use DateAdd to return a date in the future, I can not Insert or Update this result into the record.

I get various errors having to do with type mismatch or function not found, etc.

Can you see what I might be doing wrong?

Here's the code snippit:
<%
if(Recordset2.Fields.Item("SerialNo").Value <> "") then UpdateExpire__SerNo = Recordset2.Fields.Item("SerialNo").Value
if(DateAdd("d",2,Now) <> "") then UpdateExpire__XD = DateAdd("d",2,Now)
%>
<%
set UpdateExpire = Server.CreateObject("ADODB.Command")
UpdateExpire.ActiveConnection = MM_FreeVB_STRING
UpdateExpire.CommandText = "UPDATE dbo.Coupon SET ExpireDate = " + Replace(UpdateExpire__XD, "'", "''") + " WHERE SerialNo = " + Replace(UpdateExpire__SerNo, "'", "''") + ""
UpdateExpire.CommandType = 1
UpdateExpire.CommandTimeout = 0
UpdateExpire.Prepared = true
UpdateExpire.Execute()
%>

This produces this error:

Microsoft OLE DB Provider for ODBC Drivers error '80040e14'

[Microsoft][ODBC SQL Server Driver][SQL Server]Line 1: Incorrect syntax near '12'.

And it errors at the UpdateExpire.Execute() line.

The code was generated by Dreamweaver.

Thanks.

Lance

View 1 Replies


ADVERTISEMENT

Having Trouble Configuring The SqlDataSource Control's Update And Insert Commands

Jul 24, 2007

I've just finished configuring the SELECT command for the SqlDataSource in my ASP.NET 2.0 web app.  It works fine and runs against a SQL Server 2005 database, using a stored procedure that I've written.
So, then I went to configure the SqlDataSource for the UPDATE and INSERT commands, and I've written two SP's for those as well.  In the designer the second form of the wizard asks for the Select statement.  I've already given that for the SELECT statement in the third form, and I also select the INSERT tab to specify the SP I want to use for inserting data and the UPDATE tab to specify the SP I want to use for updating data.  However, there appears to be no way that I can specify what the parameters are supposed to be for anything other than the SELECT command, through the designer.  Is that correct, or have I missed something?
 

View 11 Replies View Related

Insert / Update Datetime

Sep 19, 2007

Hello All,

I am trying to insert birthdate "15/05/1981 10:45:14" into Birthday field from table. But I am receiving errror as follows

The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value.The statement has been terminated.

Does anybody know, how can I insert Or update this date?
Thanks in advance

--kneel

View 5 Replies View Related

Having Trouble Converting To Datetime In SQL Import

Jan 13, 2006

Our database gets updated each week with text files spat out by a mainframe. Previously, the database was in Access; we copied and pasted the text files into Excel, ran macros on them to convert the data, then pasted the results directly into Access and this worked fine for us.

Now that we've moved the tables to SQL Server 2000, we're having problems with the data. We wanted to set up DTS packages for each file to just put them directly into SQL Server. This works for pretty much everything except for the dates.

The way the files are set up, they're comma delimited files with quotes around the text and nothing around the dates. The dates don't have any delimiters; they're just listed like 13012006. Every time we try to import these files into SQL, it gripes about the datatypes; we're trying to put the dates into datetime fields but SQL thinks they're strings. Eek! If we put date delimiters (like 13/01/2006) SQL pulls them in fine, but apparently the mainframe lacks the ability to put these delimiters in by itself and still run everything else OK. The person who writes the extracts has to do it in a language called 'Focus' which I've never heard of and don't know anything about, and he says what I'm asking for can't be done. OK...so now what?

I've tried and tried to convert these strings into dates using both CAST() and CONVERT() and just can't manage to do it. I know I'm missing something really obvious here; does anyone have any tips or advice? Thanks in advance.

View 3 Replies View Related

Trouble With Calendar Control For Datetime Parameter

May 4, 2007

I'm creating a report with a Datetime parameter. There's no available values, so the calendar control comes out automatically when I run/preview the report. Now, when I select the date in my calendar control, say for example I select 2/5/07 (2nd of May) and run the report, it gives me data from 5th of Feb. Can anyone help me with this date format problem ???

Not sure if it's related to my problem, I did edit the language tag in the XML source code of my report to have en-AU so that the dates field is showing in the correct dd/mm/yyyy format.

View 2 Replies View Related

Trouble With Update Syntax

Jul 20, 2005

I'm new to SQL and can't figure out how to update my table(StoreItemStatus) that contains the current status for items in eachstore (STORE_KEY, ITEM_KEY, STATUS,...).I get updated status info in a table (I'll call it NewInfo) thathas similar fields. NewInfo may contain multiple records for eachStore/Item, but I will just use the latest status. I'm not sure howto update StoreItemStatus using each record of NewInfo. Any advice isgreatly appreciatedThanks,Paul

View 14 Replies View Related

Trouble With Update Query

Feb 3, 2008



I want to fill in a field whose name is stored in a variable. This code runs, but the field is not filled in afterward. I think I'm doing something wrong:


SET @field = N'bindery'

SET @ordernum = N'SM38948M08'


UPDATE Orders

SET @field = GETDATE() + 5

WHERE ordernum = @ordernum


My problem is related to using the @field variable in the UPDATE query.

How do I fix this?

Thanks!
Brian

View 8 Replies View Related

Trouble Doing Basic Insert Into Sql Db

Jul 18, 2006

i am just trying to insert a title and category row into a table in my
database, however, the page works as planned, bu no data is inserted,
and i am not getting any error messages, so i am for a loss.

here is the code for the testInsert.aspx page:

<%@ Page Explicit="True" Language="VB" Debug="True" %>
<%@ Import Namespace="System.Data"  %>
<%@ Import Namespace="System.Data.SqlClient"  %>
<html>
<body vlink="red">
<h1>title and category</h1>

<form id="Form1" runat="server">

<h2>Enter title and category</h2>

<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, _
    ByVal e As System.EventArgs)
   
        DetailsView1.ChangeMode(DetailsViewMode.Insert)
End Sub

Protected Sub DetailsView1_ItemInserted( _
    ByVal sender As Object, ByVal e As _
    System.Web.UI.WebControls.DetailsViewInsertedEventArgs)
   
        Response.Redirect("../Pages/Home.aspx")
End Sub

Protected Sub Detailsview1_ItemCommand( _
    ByVal sender As Object, ByVal e As _
    System.Web.UI.WebControls.DetailsViewCommandEventArgs)
   
        If e.commandName = "Cancel" Then
            Response.Redirect("../Pages/Home.aspx")
        End If
End Sub
</script>
Enter your e-mail address
<br />

<asp:DetailsView ID="DetailsView1" runat="server"
Height="50px" Width="100%" AutoGenerateRows="False"
DataKeyNames="AdNum" DataSourceID="SqlDataSource1"
CellPadding="4" ForeColor="#333333" GridLines="None"
OnItemInserted="DetailsView1_ItemInserted"
OnItemCommand="DetailsView1_ItemCommand">

    <Fields>
        <asp:BoundField DataField="Title"
            HeaderText="Title"
                SortExpression="Title" />
        <asp:BoundField DataField="Category"
            HeaderText="Category"
            SortExpression="Category" />
        <asp:Commandfield ButtonType="Button"
            ShowInsertButton="True" />
    </Fields>
   
    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
   
    <FieldHeaderStyle BackColor="#FFFF99" Font-Bold="True" />
   
</asp:DetailsView>

&nbsp;

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConflictDetection="CompareAllValues"
ConnectionString=
"<%$ ConnectionStrings:ASPNETDBConnectionString3 %>"
InsertCommand="INSERT INTO newInsert (Title, Category) Values(?, ?)"
ProviderName=
"<%$ ConnectionStrings:ASPNETDBConnectionString3.ProviderName %>"
SelectCommand="SELECT Title, Category FROM newInsert" >

    <InsertParameters>
        <asp:Parameter Name="Title" Type="String" />
        <asp:Parameter Name="Category" Type="String" />
    </InsertParameters>
</asp:SqlDataSource>

</form>
</body>
</html>


and here is the portion of my web.config file that references the connectionstrings:

<connectionstrings>
<add name="ASPNETDBConnectionString3" connectionString="Data
Source=.SQLEXPRESS;AttachDbFilename=&quot;C:Documents and
SettingsJordan MikoMy DocumentsVisual Studio
2005WebSitesWebSite29App_DataASPNETDB.MDF&quot;;Integrated
Security=True;Connect Timeout=30;User Instance=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

The connectionstring, table, and rows are all correctly spelled
please let me know what i am doing wrong or an easier way to do it


jordan

View 2 Replies View Related

Bulk Insert From CSV - Trouble With .FMT

Nov 8, 2006

I need to bulk insert from multiple files which are comma-separated with quotes as delimiters around each column. I cannot use DTS because the filenames are variable (unless someone knows how to get DTS to read 'DIR *.csv' and then load each file ??)

This .fmt doesn't work because SQL sees "","" as "" - meaning no terminator - then ,"" where it expects whitespace.

8.0
6
1 SQLCHAR 0 1 "","" 3 Prefix SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 1 "","" 5 Forenames SQL_Latin1_General_CP1_CI_AS
3 SQLCHAR 0 1 "","" 4 Surname SQL_Latin1_General_CP1_CI_AS
4 SQLCHAR 0 1 "","" 6 Job_Title SQL_Latin1_General_CP1_CI_AS
5 SQLCHAR 0 1 "","" 7 Org_Name SQL_Latin1_General_CP1_CI_AS
6 SQLCHAR 0 1 "","" 8 Address1 SQL_Latin1_General_CP1_CI_AS

I have tried '","' (single quote doublequote comma) to no avail.

I cannot use the obvious solution - bulk insert ... (with terminator = ' "," ') - as I need to insert all the data into specified columns of an existing table using different mappings. The .fmt file should be helping, but I cannot get past this issue.

Does anyone know how to resolve this?

View 6 Replies View Related

Trouble With An Insert Into/select Statement

Jan 2, 2008



I have several tables in a database which I always want to update with information from one table with new records (containing contact and demographical information). The setup is something like this:

NewRecordsTable: fn, ln, streetadd, city, emailadd, phonenumber, gender, birthdate

ContactTable: ID(primarykey), fn, ln, streetadd, city, state, zip, phonenumber, email

DemographicTable: ID(linked to primary key ID in Contact table), birthdate, gender


I want to update the ContactTable and DemographicTable with information from the NewRecords Table. What I have done so far is set the identity insert for the ContactTable to on, then inserted the fn, ln, streetadd, email, etc. from the NewTable. This works fine.

I then try to insert ID, birthdate and gender into the DemographicTable where NewRecordsTable.fn=ContactTable.fn AND NRT.ln=CT.ln AND NRT.streetadd=CT.streetadd AND NRT.emailadd=CT.emailadd - This mostly works, but the records which have NULL values any of those fields don't get inserted.

What I really want is to insert the records that have matching email addresses OR matching fn, ln, streetadd combos, but I can't figure out how to get that SELECT/WHERE statement to work.

The problem that underlies this is that I want to insert the ID values from the ContactTable into the DemographicTable, but the only way I can see to make them match properly is by matching the email addresses or fn, ln, streetadd combos from the NewRecordsTable to the ContactTable (all of the email addresses in our NewRecordsTable are unique, unless the person doesn't have an email address, in which case we make sure they have a unique fn, ln, streetadd combo)

Any help would be appreciated,
Thank you!!

View 3 Replies View Related

Trouble Converting Datatype For Database Insert

Dec 7, 2004

Hi,
I need to take a value from a textbox and insert it into a field in my database which takes decimals. My problem, no matter what I try I cannot convert the value so that the database will accept it. This all happens when the submit button is hit on my webpage. Here is the cmdSubmit_click sub code:

Dim surveyNum As Decimal = Decimal.Parse(txtSurveyNum.Text, Globalization.NumberStyles.Number)
myCmd.CommandText = "INSERT INTO survey(ID) VALUES('" & surveyNum & "')"
myCmd.Parameters.Add("surveyNum", SqlDbType.Decimal)
myCmd.Parameters("surveyNum").Value = System.Convert.ToDecimal(txtSurveyNum.Text)

myConn.Open()
Try
myCmd.ExecuteNonQuery()
lblMessage.Text = "Record successfully updated"
Catch
lblMessage.Text = "Query error: " & Err.Description
End Try
myConn.Close()

Thnx in advance, any help would be greatly appreciated.

View 1 Replies View Related

Trouble Converting SELECT To INSERT Statement

Sep 18, 2005

Trying to convert the following SELECT statement into a INSERT statement and having trouble. No doubt this will be a piece of cake to someone. To eventually get this to a trigger stage would be nice, but for the moment I'd settle for just plain SQL. Using MS SQL 2000. The database name is reporting. The table name is CallLog. I'm trying to convert seperate date (RecvdDate) and time (RecvdTime) columns into a single DateTime column. I've scoured a lot of web pages but I'm still lost.

==============

use reporting
go

SELECT RecvdDate + RecvdTime FROM [dbo].[CallLog]

===============

Any help much appreciated.

View 7 Replies View Related

Havin Trouble Inserting Records To A Table.. Update Works Fine

Mar 6, 2008

Hi..
I am getting a xml stream of data and putting it to a object and then calling a big sproc to insert or update data in many tables across my database... But there is one Table that i am having trouble inserting it.. But if i run an update it works fine... This my code for that part of the sproc..
 IF Exists(
SELECT
*
FROM
PlanEligibility
WHERE
PlanId = @PlanId
) BEGIN
UPDATE
PlanEligibility
SET
LengthOfService = Case When @PD_EmployeeContribution = 0 Then @rsLengthOfServicePS
ELSE @rsLengthOfService END,
EligibilityAge = CASE When @PD_EmployeeContribution = 0 Then @EligibilityAgePS Else @EligibilityAge End,
EntryDates = @EntryDates,
EligiDifferentRequirementsMatch = Case When @PD_EmployeeContribution = 0 Then 0
When @PD_EmployeeContribution = 1 and @PD_EmployerContribution = 0 then 0 Else 1 END, --@CompMatchM,
LengthOfServiceMatch = CASE When @MCompanyMatch = 0 Then @rsLengthOfServicePs ELSE @rsLengthOfServiceMatch END,
EligibilityAgeMatch = CASE When @MCompanyMatch = 0 Then @EligibilityAgePS ELSE @EligibilityAgeMatch END,
OtherEmployeeExclusions = @OtherEmployeeExclusions
WHERE
PlanId = @PlanId
END
ELSE BEGIN
INSERT INTO PlanEligibility
(
PlanId,
LengthOfService,
EligibilityAge,
EntryDates,
EligiDifferentRequirementsMatch,
LengthOfServiceMatch,
EligibilityAgeMatch,
OtherEmployeeExclusions
)
VALUES
(
@PlanId,
Case When @PD_EmployeeContribution = 0 Then @rsLengthOfServicePS
ELSE @rsLengthOfService END,--@rsLengthOfService,
CASE When @PD_EmployeeContribution = 0 Then @EligibilityAgePS Else @EligibilityAge End, --@EligibilityAge,
@EntryDates,
Case When @PD_EmployeeContribution = 0 Then 0
When @PD_EmployeeContribution = 1 and @PD_EmployerContribution = 0 then 0 Else 1 END, --having trouble here
CASE When @MCompanyMatch = 0 Then @rsLengthOfServicePs ELSE @rsLengthOfServiceMatch END,
CASE When @MCompanyMatch = 0 Then @EligibilityAgePS ELSE @EligibilityAgeMatch END, --EligibilityAgeMatch,@EligibilityAgeMatch,
@OtherEmployeeExclusions
)
END
 Any help will be appreciated..
Regards,
Karen

View 6 Replies View Related

Trouble With An ASync Query To Insert A Record And Return The Auto Number Field.

Aug 31, 2007

I get this error when I look at the state of my SQLresults object. Have I coded something wrong?Item = In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user.  conn.Open()
Dim strSql As String

strSql = "INSERT INTO contacts (companyId, sourceId, firstName, lastName, middleName, birthday, dateCreated)" _
& "VALUES ('" & companyId & "', '" & sourceId & "', '" & firstName & "', '" & lastName & "', '" & middleName & "', '" & birthday & "', '" & now & "') SELECT @@IDENTITY AS 'contactId'"

Dim objCmd As SqlCommand
objCmd = New SqlCommand(strSql, conn)

Dim aSyncResult As IAsyncResult = objCmd.BeginExecuteReader()

If aSyncResult.AsyncWaitHandle.WaitOne() = True Then


Dim sqlResults As SqlClient.SqlDataReader

sqlResults = objCmd.EndExecuteReader(aSyncResult)

Dim cid As Integer



cid = sqlResults.Item("contactId")
Me.id = cid
conn.Close()
Return cid
Else
Return "failed"


End If  

View 3 Replies View Related

SQL Server 2008 :: Update Null Enabled Field Without Interfering With Rest Of INSERT / UPDATE

Apr 16, 2015

If I have a table with 1 or more Nullable fields and I want to make sure that when an INSERT or UPDATE occurs and one or more of these fields are left to NULL either explicitly or implicitly is there I can set these to non-null values without interfering with the INSERT or UPDATE in as far as the other fields in the table?

EXAMPLE:

CREATE TABLE dbo.MYTABLE(
ID NUMERIC(18,0) IDENTITY(1,1) NOT NULL,
FirstName VARCHAR(50) NULL,
LastName VARCHAR(50) NULL,

[Code] ....

If an INSERT looks like any of the following what can I do to change the NULL being assigned to DateAdded to a real date, preferable the value of GetDate() at the time of the insert? I've heard of INSTEAD of Triggers but I'm not trying tto over rise the entire INSERT or update just the on (maybe 2) fields that are being left as null or explicitly set to null. The same would apply for any UPDATE where DateModified is not specified or explicitly set to NULL. I would want to change it so that DateModified is not null on any UPDATE.

INSERT INTO dbo.MYTABLE( FirstName, LastName, DateAdded)
VALUES('John','Smith',NULL)

INSERT INTO dbo.MYTABLE( FirstName, LastName)
VALUES('John','Smith')

INSERT INTO dbo.MYTABLE( FirstName, LastName, DateAdded)
SELECT FirstName, LastName, NULL
FROM MYOTHERTABLE

View 9 Replies View Related

Can I Insert/Update Large Text Field To Database Without Bulk Insert?

Nov 14, 2007

I have a web form with a text field that needs to take in as much as the user decides to type and insert it into an nvarchar(max) field in the database behind.  I've tried using the new .write() method in my update statement, but it cuts off the text after a while.  Is there a way to insert/update in SQL 2005 this without resorting to Bulk Insert? It bloats the transaction log and turning the logging off requires a call to sp_dboptions (or a straight-up ALTER DATABASE), which I'd like to avoid if I can.

View 6 Replies View Related

Update Datetime

Oct 4, 2006

QuestionHow can one update a DateTime field when the change request may alter any of the attributes of the time? (Day | hour | hour & minute).

WHYOf course the whole point of a timestamp is to stamp the time
of the record. The problem comes in when the user wants to tweak that
timestamp. I am not interested changing anything about the time at the seconds point. The user will only change major time factors.


Platform.Net 1xC#SQL Server 2000Eventually this will be in a Stored Procedure.

advTHANKSance

View 6 Replies View Related

T-SQL (SS2K8) :: Insert / Update Triggers When Insert Run Via Script

Oct 23, 2014

I'm working on inserting data into a table in a database. The table has two separate triggers, one for insert and one for update (I don't like it this way, but that's how it's been for years). When there is a normal insert, done via a program, it looks like the triggers work fine. When I run an insert manually via a script, the first insert trigger will run, but the update trigger will fail. I narrowed down the issue to a root cause.

This root issue is due to both triggers using the same temporary table name. When the second trigger runs, there's an error stating that a few columns don't exist. I went to my test server and test db and changed the update trigger so that the temporary table is different than the insert trigger temporary table, the triggers work fine. The weird thing is that if the temporary table already exists, when the second trigger tries to create the temporary table, I would expect it to fail and say that it already exists.I'm probably just going to update the trigger tonight and change the temporary table name.

View 1 Replies View Related

Insert Datetime, Using ADO.net VB.net

Feb 16, 2008

Hello there,I got a little code there are inserting a record into my msSQL database..But i cant insert the datetime, for one reason?The problem is in line 7 () where i want to insert DateTime.Now 1 Protected Sub SendPmTilAfviste(ByVal modtager As String, ByVal festID As String)
2 ' Connection
3 Dim conn As SqlConnection = New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|ASPNETDB.MDF;Integrated Security=True;User Instance=True")
4 conn.Open()
5
6 ' SQL-kommandoen
7 Dim cmd As SqlCommand = New SqlCommand("INSERT INTO marcisoft_PMsystem(laest,fra,modtager,sendt,overskrift,besked) VALUES('<b>Ny!</b>','webmaster1','" + modtager + "','" + DateTime.Now + "','A headline','text text the id " + festID + "')", conn)
8 cmd.ExecuteNonQuery()
9
10 conn.Close()
11 conn = Nothing
12
13 End Sub
 If i using with ' aroundIt show up with a error, out of range..And if i dont, it show up with another error, problem near 02(02 could be the clock or the month, think clock)Hope someone knows how this is done..

View 4 Replies View Related

SQLAdapter Update And Datetime

Mar 13, 2008

Hey,

I have a case where I fill a datatable with two column wich contain
datetime. Il filled them and everything seems alright in debug. Problem
is that when I update with the SQLAdapter, it says that it cannot
insert NULL into a datetime column, but the fact is that it is not NULL.

Here what it looks like:

SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["BD"]);

conn.Open();



adapter.InsertCommand = new SqlCommand("Commun.SP__PeriodeEnregistrer", conn);
adapter.InsertCommand.CommandType = CommandType.StoredProcedure;
adapter.InsertCommand.Parameters.Add("@idperiode", SqlDbType.Int, 10, "IDPeriode");
adapter.InsertCommand.Parameters.Add("@nosemaine", SqlDbType.Int,10,"NoSemaine");
adapter.InsertCommand.Parameters.Add("@annee", SqlDbType.Int, 10, "Annee");
adapter.InsertCommand.Parameters.Add("@periode", SqlDbType.Int, 10, "Periode_no");
adapter.InsertCommand.Parameters.Add("@datedebut", SqlDbType.DateTime, 150, "Debut_date");
adapter.InsertCommand.Parameters.Add("@datefin", SqlDbType.DateTime, 150, "Fin_date");
adapter.Update(dtPeriode);

Thanks in advance

View 3 Replies View Related

Update A Datetime Column

Apr 20, 2005

I'm trying to update a datetime column from another datetime column. However, I just want the date transferred to the new column without the time. Any ideas? Thanks for your help.

View 6 Replies View Related

Update Datetime Field??

Apr 6, 2006

hello friend !!

i want to update date field but i am getting error like

update emp set convert(varchar(50),date_t,121) = '2006-03-31 19:56:36.933'
Server: Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'convert'.

please help me out

T.I.A

Shashank

View 20 Replies View Related

How To Update A Datetime Field

Jul 23, 2005

How can I update only the date portion of a datetime field?Example:datetime field = '3/12/1995 12:05:50 PM'How can I change just the day '12' to a '7'Thanks

View 4 Replies View Related

Update ONLY Time On DateTime

May 20, 2008

Hi,

I have a DateTime Column and I need to update the Time Part of it, without changing the Date Part.

For Example:

STARTDATE:
04.08.2008 12:30:00

UPDATE TO:
04.08.2008 14:40:00

I tried something like:
UPDATE table SET STARTDATE = '14:40:00' WHERE GUID = '{82F99509-3C44-4D24-96D0-CF3753C0C353}'

But this will also change the Date to 1.1.1900.

Any advise?

View 5 Replies View Related

Update Datetime Into Database

Feb 7, 2008



I have Log table for employees
columns :
EmployeeID - int
In - DateTime
Out - DateTime

When employee come ,he press button and program insert new row ( EmployeeID and In )
when he go out he press button and my problem begin :
How to UPDATE exactly that row with that EmployeeID and lastest day when he came ?

View 3 Replies View Related

Trigger To Update A Table On Insert Or Update

Feb 15, 2008



Hello

I've to write an trigger for the following action

When a entry is done in the table Adoscat79 having in the index field Statut_tiers the valeur 1 and a date in data_cloture for a customer xyz

all the entries in the same table where the no_tiers is the same as the one entered (many entriers) should have those both field updated

statut_tiers to 1
and date_cloture to the same date as entered

the same action has to be done when an update is done and the valeur is set to 1 for the statut_tiers and a date entered in the field date_clture

thank you for your help
I've never done a trigger before

View 14 Replies View Related

Single Complex INSERT Or INSERT Plus UPDATE

Jul 23, 2005

Hello,I am writing a stored procedure that will take data from severaldifferent tables and will combine the data into a single table for ourdata warehouse. It is mostly pretty straightforward stuff, but there isone issue that I am not sure how to handle.The resulting table has a column that is an ugly concatenation fromseveral columns in the source. I didn't design this and I can't huntdown and kill the person who did, so that option is out. Here is asimplified version of what I'm trying to do:CREATE TABLE Source (grp_id INT NOT NULL,mbr_id DECIMAL(18, 0) NOT NULL,birth_date DATETIME NULL,gender_code CHAR(1) NOT NULL,ssn CHAR(9) NOT NULL )GOALTER TABLE SourceADD CONSTRAINT PK_SourcePRIMARY KEY CLUSTERED (grp_id, mbr_id)GOCREATE TABLE Destination (grp_id INT NOT NULL,mbr_id DECIMAL(18, 0) NOT NULL,birth_date DATETIME NULL,gender_code CHAR(1) NOT NULL,member_ssn CHAR(9) NOT NULL,subscriber_ssn CHAR(9) NOT NULL )GOALTER TABLE DestinationADD CONSTRAINT PK_DestinationPRIMARY KEY CLUSTERED (grp_id, mbr_id)GOThe member_ssn is the ssn for the row being imported. Each member alsohas a subscriber (think of it as a parent-child kind of relationship)where the first 9 characters of the mbr_id (as a zero-padded string)match and the last two are "00". For example, given the followingmbr_id values:1234567890012345678901123456789021111111110022222222200They would have the following subscribers:mbr_id subscriber mbr_id12345678900 1234567890012345678901 1234567890012345678902 1234567890011111111100 1111111110022222222200 22222222200So, for the subscriber_ssn I need to find the subscriber using theabove rule and fill in that ssn.I have a couple of ideas on how I might do this, but I'm wondering ifanyone has tackled a similar situation and how you solved it.The current system does an insert with an additional column for thesubscriber mbr_id then it updates the table using that column to joinback to the source. I could also join the source to itself in the firstplace to fill it in without the extra update, but I'm not sure if theextra complexity of the insert statement would offset any gains fromputting it all into one statement. I plan to test that on Monday.Thanks for any ideas that you might have.-Tom.

View 4 Replies View Related

How To Insert A Datetime To Sql Sever

Aug 30, 2006

Hi everyone,I need help in inserting a date time string to sql sever.  For example, how do you insert textbox1.text="2006-08-30 09:00:00" into a datatable column names starttime (type datetime) in sql sever?  How do I covert the format of this string before I do the insert?Thanks.a123.

View 2 Replies View Related

How To Insert A Datetime Into Sql Sever

Aug 30, 2006

Hi everyone,How do you insert this string value lable1.text="2006-08-30 09:00:00" into  a data column like startdate (type: datetime) in sql sever?How do I convert this string value before I insert it into sql sever? Thank you very much.a123.

View 1 Replies View Related

Insert NULL Value Into DateTime

Dec 11, 2006

Does anyone have a simple way of inserting a NULL value into sql 2000 datetime. I'm using vb.net.
All I want is if the user does not enter a date in a textbox to to send a NULL value to the DB instead of having the db enter the default value as 1/1/1900.
Thank you

View 3 Replies View Related

Insert DateTime Into SQL Server Using C#

Jan 13, 2004

Hi,

I have very little C# experience and I am in over my head here. This script will insert all data into the data base after I have removed all refference to the date.

I know I have to change the datatype in code, but I have tried everything I can think of.

Any suggestion would be greatly appreciated.

The .aspx.cs file is below:



using System;
using System.Configuration;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;



namespace News
{
public class AddNews : System.Web.UI.Page
{
protected System.Web.UI.HtmlControls.HtmlInputText txt_news_title;
protected System.Web.UI.WebControls.TextBox txt_news_body;
protected System.Web.UI.HtmlControls.HtmlInputFile txt_news_image;
protected System.Web.UI.WebControls.Button UploadBtn;
protected System.Web.UI.WebControls.Button ResetBtn;
protected System.Web.UI.WebControls.RequiredFieldValidator rfv_news_image;
protected System.Web.UI.WebControls.Label lbl_news_result;

public AddNews() { }


private void Page_Load(object sender, System.EventArgs e)
{}


public void UploadBtn_Click(object sender, System.EventArgs e)
{
if (Page.IsValid) //save the image
{

//news_title
string newsTitle = txt_news_title.Value;

//news_body
string newsBody = txt_news_body.Text;

//news_date
DateTime dtCurrTime = DateTime.Today;
string d = dtCurrTime.ToString();

//news_img & news_imgcontenttype
Stream imgStream = txt_news_image.PostedFile.InputStream;
int imgLen = txt_news_image.PostedFile.ContentLength;
string imgContentType = txt_news_image.PostedFile.ContentType;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData,0,imgLen);

int RowsAffected = SaveToDB( newsTitle,newsBody,d,imgBinaryData,imgContentType);
if ( RowsAffected>0 )
{
//Response.Write("<BR>The Image was saved");
lbl_news_result.Text = "Record was added successfully!";
txt_news_title.Value = "";
txt_news_body.Text = "";
}
else
{
//Response.Write("<BR>An error occurred uploading the image");
lbl_news_result.Text = "Record was NOT added!";
}
}
}

public void Reset_Click(object sender, System.EventArgs e)
{
txt_news_title.Value = "";
txt_news_body.Text = "";
lbl_news_result.Text = "";


}




private int SaveToDB(string newsTitle, string newsBody, string d, byte[] imgbin, string imgcontenttype)
{
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["connString"]);


SqlCommand command = new SqlCommand( "INSERT INTO Cover (cover_title,cover_body,cover_date,cover_image,cover_imgcontenttype) VALUES ( @news_title,@news_body,@news_date,@img_data,@img_contenttype )", connection );

SqlParameter param0 = new SqlParameter( "@news_title", SqlDbType.VarChar,50 );
param0.Value = newsTitle;
command.Parameters.Add( param0 );

SqlParameter param1 = new SqlParameter( "@news_body", SqlDbType.VarChar,5000 );
param1.Value = newsBody;
command.Parameters.Add( param1 );

SqlParameter param2 = new SqlParameter( "@news_date", SqlDbType.VarChar,8 );
param2.Value = d;
command.Parameters.Add( param2 );


SqlParameter param3 = new SqlParameter( "@img_data", SqlDbType.Image );
param3.Value = imgbin;
command.Parameters.Add( param3 );

SqlParameter param4 = new SqlParameter( "@img_contenttype", SqlDbType.VarChar,50 );
param4.Value = imgcontenttype;
command.Parameters.Add( param4 );

connection.Open();

int numRowsAffected = command.ExecuteNonQuery();

connection.Close();

return numRowsAffected;
}
}
}




Thanks!

View 5 Replies View Related

Insert Datetime In SQL Server?

Feb 12, 2004

Hi there,

Just a simple question for the .NET geeks out there.....how do I insert datetime format in MS SQL Server 7.0?

Thank you!

View 3 Replies View Related

Datetime Format (insert From Vb6)

Apr 12, 2000

I'm still having a problem inserting date fields into sql server.

I don't understand how it accepts datetime.

I have all of my date columns defined with datetime format and all of the dates are coming out as the default of: 01/01/1900.

I tried to insert the data as string and sql server doesn't understand that format.
Here's some of the code:

We're going from flat VSAM files to an sql server database.
This is one huge sql insert statement with about 75 fields being loaded into a table so I'll only post one the date fields.
Here's where I call the String functions from:

First, I have to uncomp the field from binary to String:

ls_sdate = Right$(CompToStr(bufMast.Name_Chg_Date), 8)

And then I send this string to my Convert_Date function:

lsDet1 = Trim$(lsDet1) & Convert_Date(ls_sdate) & ","

(lsDet1 is a concatenated String of the SQL Values to be inserted)

And Here are the two functions:
The date field is coming in like: 1991112 where if the first character is a 1, the year is 1900 and if the first character is a 0, the year is 2000.
I get correct fields in my message box like 1996/12/31 but then I don't know what sql server does to it in datetime format.
When I check the database table it looks like: 01/12/1900

Maybe there is something wrong with my Convert_Date function;

__________________________________________________ ____________

Public Function CompToStr(aCompdata() As Byte) As String
'This is one way in which you can unpack a comp field. As I mentioned,
'you might be better off designing a flexible class to do the
'conversions. At minimum, this function should be expanded to
'accept a data picture as a param (decimal placement and so on).

Dim lsRtnStr As String
Dim lsHoldStr As String
Dim llCount As Long

For llCount = 1 To (UBound(aCompdata) + 1) Step 1 'loop thru the passed array.
lsHoldStr = Hex(aCompdata(llCount - 1)) 'Convert the byte to a Hex string.
If Len(Trim$(lsHoldStr)) = 1 Then 'if the highorder nibble was 0
lsHoldStr = "0" & Trim$(lsHoldStr) 'pad it with a leading zero.
End If
lsRtnStr = lsRtnStr & lsHoldStr 'Concat it to the return string.
lsHoldStr = "" 'clear the var for the next pass.
Next
lsRtnStr = Replace$(lsRtnStr, "C", " ") 'Positive sign replacement.
lsRtnStr = Replace$(lsRtnStr, "D", "-") 'Negative sign replacement.
lsRtnStr = Replace$(lsRtnStr, "F", " ") 'Unsigned - implicit positive.
lsRtnStr = Trim$(lsRtnStr)

llCount = 0
llCount = InStr(1, lsRtnStr, "-")

If llCount > 0 Then
lsRtnStr = Right$(lsRtnStr, 1) & Left$(lsRtnStr, (Len(lsRtnStr) - 1))
End If
CompToStr = lsRtnStr 'Return the hex string.
End Function
__________________________________________________ ___________________

Public Function Convert_Date(ByRef ls_sdate As String) As String

'incoming date
Dim ls_scent
, ls_smonth, ls_sday, ls_syear As String

ls_scent = Left(ls_sdate, 1)
ls_syear = Mid(ls_sdate, 2, 2)
ls_smonth = Mid(ls_sdate, 4, 2)
ls_sday = Right(ls_sdate, 2)

If (ls_sday = "00") Then
ls_sdate = "0000"
ElseIf (ls_scent = 0) Then
'ls_sdate = ls_smonth & "/" & ls_sday & "/" & "19" & ls_syear
ls_sdate = "19" & ls_syear & "/" & ls_smonth & "/" & ls_sday
ElseIf (ls_scent = 1) Then
'ls_sdate = ls_smonth & "/" & ls_sday & "/" & "20" & ls_syear
ls_sdate = "20" & ls_syear & "/" & ls_smonth & "/" & ls_sday
End If

Convert_Date = ls_sdate

End Function
__________________________________________________ ____________

View 1 Replies View Related







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