INSERT Statement For Datetime .

Feb 9, 2005

In Oracle , v can use select and insert for a date column as below:

for select :
----------------------------------------------------------------
select A,to_char(CDATE,'DD-MM-YY:HH:MI:SS AM') from db.table1;

for insert:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
insert into db.table1
(A,CDATE)
values
( 2, TO_Date('20/01/2005 11:08:33 PM', 'DD/MM/YYYY HH:MI:SS AM'));
----------------------------------------------------------------


But How v can use datetime in MSSQL Server ?
What are the corresponding select and insert statement in this ?

Any one have idea in this ?

thanks

View 4 Replies


ADVERTISEMENT

Insert Statement For Datetime Column Fails

Oct 16, 2006

I ve a simple table with a column of type datetime. I ve successfully inserted the following values in it,

2006-09-13 18:00:10
2006-09-14 18:00:10
2006-09-15 18:00:10


however, it fails when i try to insert the value 0000-00-00 00:00:00. ie., the following insert statement fails

INSERT INTO TEST VALUES('0000-00-00 00:00:00')

The error thrown is,

Server Msg 242, Level 16, State 3, Line 1
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.

View 13 Replies View Related

Using Datetime Value In Insert Statement In Stored Procedure

Apr 26, 2008



I want to store datetime data in data table.

I am facing problem in using datetime data value in insert statement passed via stored procedure.
Any Help !Thanks in advance

View 3 Replies View Related

DB Engine :: Can't Use The MERGE Statement / How To Design WHERE Condition For Insert Statement

Nov 5, 2015

I've have a need with SQL Server 2005 (so I've no MERGE statement), I have to merge 2 tables, the target table has 10 fields, the first 4 are the clustered index and primary key, the source table has the same fields and index.Since I can't use the MERGE statement (I'm in SQL 2005) I have to make a double step operation, and INSERT and an UPDATE, I can't figure how to design the WHERE condition for the insert statement.

View 2 Replies View Related

Strange Problem: SQL Insert Statement Does Not Insert All The Fields Into Table From Asp.net C# Webpage

Apr 21, 2008

An insert statement was not inserting all the data into a table. Found it very strange as the other fields in the row were inserted. I ran SQL profiler and found that sql statement had all the fields in the insert statement but some of the fields were not inserted. Below is the sql statement which is created dyanmically by a asp.net C# class. The columns which are not inserted are 'totaltax' and 'totalamount' ...while the 'shipto_name' etc...were inserted.there were not errors thrown. The sql from the code cannot be shown here as it is dynamically built referencing C# class files.It works fine on another test database which uses the same dlls. The only difference i found was the difference in date formats..@totalamount=1625.62,@totaltax=125.62are not inserted into the database.Below is the statement copied from SQL profiler.exec sp_executesql N'INSERT INTO salesorder(billto_city, billto_country, billto_line1, billto_line2, billto_name,billto_postalcode, billto_stateorprovince, billto_telephone, contactid, CreatedOn, customerid, customeridtype,DeletionStateCode, discountamount, discountpercentage, ModifiedOn, name, ordernumber,pricelevelid, salesorderId, shipto_city, shipto_country,shipto_line1, shipto_line2, shipto_name, shipto_postalcode, shipto_stateorprovince,shipto_telephone, StateCode, submitdate, totalamount,totallineitemamount, totaltax ) VALUES(@billto_city, @billto_country, @billto_line1, @billto_line2,@billto_name, @billto_postalcode, @billto_stateorprovince, @billto_telephone, @contactid, @CreatedOn, @customerid,@customeridtype, @DeletionStateCode, @discountamount,@discountpercentage, @ModifiedOn, @name, @ordernumber, @pricelevelid, @salesorderId,@shipto_city, @shipto_country, @shipto_line1, @shipto_line2,@shipto_name, @shipto_postalcode, @shipto_stateorprovince, @shipto_telephone,@StateCode, @submitdate, @totalamount, @totallineitemamount, @totaltax)',N'@billto_city nvarchar(8),@billto_country nvarchar(13),@billto_line1 nvarchar(3),@billto_line2 nvarchar(4),@billto_name nvarchar(15),@billto_postalcode nvarchar(5),@billto_stateorprovince nvarchar(8),@billto_telephone nvarchar(3),@contactid uniqueidentifier,@CreatedOn datetime,@customerid uniqueidentifier,@customeridtype int,@DeletionStateCode int,@discountamount decimal(1,0),@discountpercentage decimal(1,0),@ModifiedOn datetime,@name nvarchar(33),@ordernumber nvarchar(18),@pricelevelid uniqueidentifier,@salesorderId uniqueidentifier,@shipto_city nvarchar(8),@shipto_country nvarchar(13),@shipto_line1 nvarchar(3),@shipto_line2 nvarchar(4),@shipto_name nvarchar(15),@shipto_postalcode nvarchar(5),@shipto_stateorprovince nvarchar(8),@shipto_telephone nvarchar(3),@StateCode int,@submitdate datetime,@totalamount decimal(6,2),@totallineitemamount decimal(6,2),@totaltax decimal(5,2)',@billto_city=N'New York',@billto_country=N'United States',@billto_line1=N'454',@billto_line2=N'Road',@billto_name=N'Hillary Clinton',@billto_postalcode=N'10001',@billto_stateorprovince=N'New York',@billto_telephone=N'124',@contactid='8DAFE298-3A25-42EE-B208-0B79DE653B61',@CreatedOn=''2008-04-18 13:37:12:013'',@customerid='8DAFE298-3A25-42EE-B208-0B79DE653B61',@customeridtype=2,@DeletionStateCode=0,@discountamount=0,@discountpercentage=0,@ModifiedOn=''2008-04-18 13:37:12:013'',@name=N'E-Commerce Order (Before billing)',@ordernumber=N'BRKV-CC-OKRW5764YS',@pricelevelid='B74DB28B-AA8F-DC11-B289-000423B63B71',@salesorderId='9CD0E11A-5A6D-4584-BC3E-4292EBA6ED24',@shipto_city=N'New York',@shipto_country=N'United States',@shipto_line1=N'454',@shipto_line2=N'Road',@shipto_name=N'Hillary Clinton',@shipto_postalcode=N'10001',@shipto_stateorprovince=N'New York',@shipto_telephone=N'124',@StateCode=0,@submitdate=''2008-04-18 14:37:10:140'',@totalamount=1625.62,@totallineitemamount=1500.00,@totaltax=125.62
 
thanks

View 7 Replies View Related

Cannot INSERT Data To 3 Tables Linked With Relationship (INSERT Statement Conflicted With The FOREIGN KEY Constraint Error)

Apr 9, 2007

Hello
 I have a problem with setting relations properly when inserting data using adonet. Already have searched for a solutions, still not finding a mistake...
Here's the sql management studio diagram :

 and here goes the  code1 DataSet ds = new DataSet();
2
3 SqlDataAdapter myCommand1 = new SqlDataAdapter("select * from SurveyTemplate", myConnection);
4 SqlCommandBuilder cb = new SqlCommandBuilder(myCommand1);
5 myCommand1.FillSchema(ds, SchemaType.Source);
6 DataTable pTable = ds.Tables["Table"];
7 pTable.TableName = "SurveyTemplate";
8 myCommand1.InsertCommand = cb.GetInsertCommand();
9 myCommand1.InsertCommand.Connection = myConnection;
10
11 SqlDataAdapter myCommand2 = new SqlDataAdapter("select * from Question", myConnection);
12 cb = new SqlCommandBuilder(myCommand2);
13 myCommand2.FillSchema(ds, SchemaType.Source);
14 pTable = ds.Tables["Table"];
15 pTable.TableName = "Question";
16 myCommand2.InsertCommand = cb.GetInsertCommand();
17 myCommand2.InsertCommand.Connection = myConnection;
18
19 SqlDataAdapter myCommand3 = new SqlDataAdapter("select * from Possible_Answer", myConnection);
20 cb = new SqlCommandBuilder(myCommand3);
21 myCommand3.FillSchema(ds, SchemaType.Source);
22 pTable = ds.Tables["Table"];
23 pTable.TableName = "Possible_Answer";
24 myCommand3.InsertCommand = cb.GetInsertCommand();
25 myCommand3.InsertCommand.Connection = myConnection;
26
27 ds.Relations.Add(new DataRelation("FK_Question_SurveyTemplate", ds.Tables["SurveyTemplate"].Columns["id"], ds.Tables["Question"].Columns["surveyTemplateID"]));
28 ds.Relations.Add(new DataRelation("FK_Possible_Answer_Question", ds.Tables["Question"].Columns["id"], ds.Tables["Possible_Answer"].Columns["questionID"]));
29
30 DataRow dr = ds.Tables["SurveyTemplate"].NewRow();
31 dr["name"] = o[0];
32 dr["description"] = o[1];
33 dr["active"] = 1;
34 ds.Tables["SurveyTemplate"].Rows.Add(dr);
35
36 DataRow dr1 = ds.Tables["Question"].NewRow();
37 dr1["questionIndex"] = 1;
38 dr1["questionContent"] = "q1";
39 dr1.SetParentRow(dr);
40 ds.Tables["Question"].Rows.Add(dr1);
41
42 DataRow dr2 = ds.Tables["Possible_Answer"].NewRow();
43 dr2["answerIndex"] = 1;
44 dr2["answerContent"] = "a11";
45 dr2.SetParentRow(dr1);
46 ds.Tables["Possible_Answer"].Rows.Add(dr2);
47
48 dr1 = ds.Tables["Question"].NewRow();
49 dr1["questionIndex"] = 2;
50 dr1["questionContent"] = "q2";
51 dr1.SetParentRow(dr);
52 ds.Tables["Question"].Rows.Add(dr1);
53
54 dr2 = ds.Tables["Possible_Answer"].NewRow();
55 dr2["answerIndex"] = 1;
56 dr2["answerContent"] = "a21";
57 dr2.SetParentRow(dr1);
58 ds.Tables["Possible_Answer"].Rows.Add(dr2);
59
60 dr2 = ds.Tables["Possible_Answer"].NewRow();
61 dr2["answerIndex"] = 2;
62 dr2["answerContent"] = "a22";
63 dr2.SetParentRow(dr1);
64 ds.Tables["Possible_Answer"].Rows.Add(dr2);
65
66 myCommand1.Update(ds,"SurveyTemplate");
67 myCommand2.Update(ds, "Question");
68 myCommand3.Update(ds, "Possible_Answer");
69 ds.AcceptChanges();
70

and that causes (at line 67):"The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_Question_SurveyTemplate". The conflict occurred in database
"ankietyzacja", table "dbo.SurveyTemplate", column
'id'.
The statement has been terminated.
at System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.Update(DataSet dataSet, String srcTable)
at AnkietyzacjaWebService.Service1.createSurveyTemplate(Object[] o) in J:\PL\PAI\AnkietyzacjaWebService\AnkietyzacjaWebServicece\Service1.asmx.cs:line 397"


Could You please tell me what am I missing here ?
Thanks a lot.
 

View 5 Replies View Related

Interaction Between Instead Of Insert Trigger And Output Clause Of Insert Statement

Jan 14, 2008


This problem is being seen on SQL 2005 SP2 + cumulative update 4

I am currently successfully using the output clause of an insert statement to return the identity values for inserted rows into a table variable

I now need to add an "instead of insert" trigger to the table that is the subject of the insert.

As soon as I add the "instead of insert" trigger, the output clause on the insert statement does not return any data - although the insert completes successfully. As a result I am not able to obtain the identities of the inserted rows

Note that @@identity would return the correct value in the test repro below - but this is not a viable option as the table in question will be merge replicated and @@identity will return the identity value of a replication metadata table rather than the identity of the row inserted into my_table

Note also that in the test repro, the "instead of insert" trigger actually does nothing apart from the default insert, but the real world trigger has additional code.

To run the repro below - select each of the sections below in turn and execute them
1) Create the table
2) Create the trigger
3) Do the insert - note that table variable contains a row with column value zero - it should contain the @@identity value
4) Drop the trigger
5) Re-run the insert from 3) - note that table variable is now correctly populated with the @@identity value in the row

I need the behaviour to be correct when the trigger is present

Any thoughts would be much appreciated

aero1


/************************************************
1) - Create the table
************************************************/
CREATE TABLE [dbo].[my_table](
[my_table_id] [bigint] IDENTITY(1,1) NOT NULL,
[forename] [varchar](100) NULL,
[surname] [varchar](50) NULL,
CONSTRAINT [pk_my_table] PRIMARY KEY NONCLUSTERED
(
[my_table_id] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, FILLFACTOR = 70) ON [PRIMARY]
)

GO
/************************************************
2) - Create the trigger
************************************************/
CREATE TRIGGER [dbo].[trig_my_table__instead_insert] ON [dbo].[my_table]
INSTEAD OF INSERT
AS
BEGIN

INSERT INTO my_table
(
forename,
surname)
SELECT
forename,
surname
FROM inserted

END

/************************************************
3) - Do the insert
************************************************/

DECLARE @my_insert TABLE( my_table_id bigint )

declare @forename VARCHAR(100)
declare @surname VARCHAR(50)

set @forename = N'john'
set @surname = N'smith'

INSERT INTO my_table (
forename
, surname
)
OUTPUT inserted.my_table_id INTO @my_insert
VALUES( @forename
, @surname
)

select @@identity -- expect this value in @my_insert table
select * from @my_insert -- OK value without trigger - zero with trigger

/************************************************
4) - Drop the trigger
************************************************/

drop trigger [dbo].[trig_my_table__instead_insert]
go

/************************************************
5) - Re-run insert from 3)
************************************************/
-- @my_insert now contains row expected with identity of inserted row
-- i.e. OK

View 5 Replies View Related

Using DateTime In WHERE Statement Help

Jan 31, 2008

Hi everyone I am having some query trouble using a DateTime field in a WHERE statement. Basically, I have a field which holds a DateTime value and want to delete records that are greater than that value inside the DateTime field. For example:

DELETE FROM Table1 WHERE JobDateTime > 01/02/2008 12:00:00

Is this possible? I get the following error when trying to do this:





Code Snippet
Incorrect syntax near '12:00:00'.
Appreciate the help. Regards, Onam

View 11 Replies View Related

Case Statement Error In An Insert Statement

May 26, 2006

Hi All,
I've looked through the forum hoping I'm not the only one with this issue but alas, I have found nothing so I'm hoping someone out there will give me some assistance.
My problem is the case statement in my Insert Statement. My overall goal is to insert records from one table to another. But I need to be able to assign a specific value to the incoming data and thought the case statement would be the best way of doing it. I must be doing something wrong but I can't seem to see it.

Here is my code:
Insert into myTblA
(TblA_ID,
mycasefield =
case
when mycasefield = 1 then 99861
when mycasefield = 2 then 99862
when mycasefield = 3 then 99863
when mycasefield = 4 then 99864
when mycasefield = 5 then 99865
when mycasefield = 6 then 99866
when mycasefield = 7 then 99867
when mycasefield = 8 then 99868
when mycasefield = 9 then 99855
when mycasefield = 10 then 99839
end,
alt_min,
alt_max,
longitude,
latitude
(
Select MTB.LocationID
MTB.model_ID
MTB.elevation, --alt min
null, --alt max
MTB.longitude, --longitude
MTB.latitude --latitude
from MyTblB MTB
);

The error I'm getting is:
Incorrect syntax near '='.

I have tried various versions of the case statement based on examples I have found but nothing works.
I would greatly appreciate any assistance with this one. I've been smacking my head against the wall for awhile trying to find a solution.

View 10 Replies View Related

How To Use Select Statement Inside Insert Statement

Oct 20, 2014

In the below code i want to use select statement for getting customer

address1,customeraddress2,customerphone,customercity,customerstate,customercountry,customerfirstname,customerlastname

from customer table.Rest of the things will be as it is in the following code.How do i do this?

INSERT INTO EMImportListing ("
sql += " CustId,Title,Description,JobCity,JobState,JobPostalCode,JobCountry,URL,Requirements, "
sql += " IsDraft,IsFeatured,IsApproved,"
sql += " Email,OrgName,customerAddress1,customerAddress2,customerCity,customerState,customerPostalCode,

[code]....

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

Converting Datetime Formats - Select Statement?

Mar 20, 2014

I have a datetime format that comes in 'yyyy-mm-dd hh:mm:ss.nnn'

But I only want 'yyyy-mm'

I am not sure how to correctly write the select statements. Below is what I have..

How would I do this, so the datetime result is 'mmmm-yy' ....

SELECT
[RecordingDate],
[RecordedUserID],
[CombindedPercentieScore]
FROM [dbo].[scoringsummary]

WHERE convert(varchar(7), [RecordingDate],120) between convert(varchar(7), DateAdd(dd,-180,GetDate()), 120) AND convert(varchar(7), DateAdd(dd,-1,GetDate()), 120)

View 2 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

Trigger: Insert Datetime

Dec 14, 2005

I'm new to SQL and I'm trying to write a trigger to input the current date/time only on insert.

Can someone help, it seems my syntax is wrong. I've tried it many different ways.

Here's my latest:

select * from inserted set productiondetail.datestamp = getdate(now)

Thanks,

Ronna

View 14 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

Insert Datetime Problem

Jul 23, 2005

How do i insert this string "23:58:44.000 UTC Wed May 11 2005" into thedatabase with datetime data format...I tried using:insert into table (startime) values ('23:58:44.000 UTC Wed May 112005')but got Syntax error converting datetime from character string error.So how do i do it??? Thx.

View 1 Replies View Related

Insert/select Datetime

Apr 4, 2008



Hello,
What is the query for inserting a data and time value for sql ce?
and how can i select the rows that are between 2 date values?
have tried everything but cant make it work..
thnx in advance.
by the way i am using sql mobile 2005 and vs2005..

View 4 Replies View Related

INSERT NULL Value + DateTime

Dec 10, 2007

Hi,

If a datetime variable is empty I want to insert null into the database table.

How do i do this? Below code doesn't work. Get this error...
Cannot implicitly convert type 'System.DBNull' to 'System.DateTime'




Code Block
if (myDataGridView.Rows[iRow].Cells["myDateDataGridViewTextBoxColumn"].Value.ToString() != "")
{
myDateReport = DateTime.Parse(myDataGridView.Rows[iRow].Cells["myDateDataGridViewTextBoxColumn"].Value.ToString());
}
else
{
myDateReport = DBNull.Value;
}

View 2 Replies View Related

Problem When Insert DateTime To DataBase

May 16, 2007

 
the column type of stime and etime in Dabase both are datetime
--------------------------------------------------------------------------------------------------
     public DateTime loginTime    {        get        {
            //got user enter page's time            return DateTime.Now;        }        }
 
//record user's using time when user click exit button 
    protected void Button1_Click(object sender, EventArgs e)    { 
            int Member_No = Int32.Parse(cls_login2.GetCurrent_login_Member_no(this.Page));            int Lesson_No = Int32.Parse(Lesson_no);            int Prestep = 1;            string RemoteIp = Request.ServerVariables["REMOTE_ADDR"].ToString();
            string sqlConn = "Insert into pro_Study_log (Member_no,Lesson_no,Study_log_stepid,Study_log_stime,Study_log_etime,Study_log_ip) ";            sqlConn += "values(" + Member_No + "," + Lesson_No + "," + Prestep + "," + loginTime + ", getdate(), '" + RemoteIp + "')";            SqlConnection connLog = new SqlConnection(StrConn);
            SqlCommand cmdLog = new SqlCommand(sqlConn, connLog);            cmdLog.CommandType = CommandType.Text;            connLog.Open();            cmdLog.ExecuteNonQuery();            connLog.Close();
-----------------------
and then I got error message on column Study_log_stime
I also trid   set the dateimt tostring , still doesn't work..
 
I don't know where I did wrong... pleae help
 many thanks
 
 

View 2 Replies View Related

What Do I Have To Convert DateTime To , To Insert It In A CommandText

Mar 26, 2008

I keep trying to insert a Value in a field called Category and DateTIme in a field called date but I keep getting this error
The datetime field in the database is a data type DateTime. I converted the varible  into a ToString, I put it in a Convert.In32() method, I even set the varible to a DateTime datatype. doesnt work. whats wrong ?
Server Error in '/WebSite1' Application.


Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS1502: The best overloaded method match for 'System.Data.SqlClient.SqlParameterCollection.AddWithValue(string, object)' has some invalid argumentsSource Error:





Line 33: cmd.Parameters.AddWithValue("@Category", NewCat.Text);
Line 34: DateTime Date = DateTime.Now;
Line 35: cmd.Parameters.AddWithValue("@Date",Date.ToString);
Line 36:
Line 37: trySource File: c:Documents and SettingsCompaq_OwnerMy DocumentsVisual Studio 2008WebSitesWebSite1AdminCat.aspx.cs    Line: 35
Show Detailed Compiler Output:

View 5 Replies View Related

Insert TIME Only In DateTime Field

Jun 23, 2004

I am doing a temporary retro-upgrade right now. So, I know this isn't exactly in the scope of ASP.Net. Ordinally my posts are. However, I need a VBScript example of how to insert the Date only into the DateTime field of an SQL 2000 Server. By default, if you try to, the server automatically adds the date "1/1/1900". Can anyone help me please?

View 2 Replies View Related

Cant Insert NULL To DateTime Field

Jun 5, 2006

Hi I'm using DetailView and I have a text box which show the date. I have formated the date as shortDate {0:d} format. I want to insert/update null if that text box is empty.
I have tried putting null value in my Update statement in sqlDataSource. And I'm getting error saying can't convert varchar to smalldatetime.
If I don't set null value as above, some large date (01/01/2033) has been inserted in my database.
Can anyone help me?
Moe

View 5 Replies View Related

Insert Time Into DateTime Field

Apr 5, 1999

I would like to be able to insert a time value only into a SQL 7 table colum which has been set as a datetime datatype. When I insert '12:34:44 PM' into the colum it actually inserts '1900-1-1 12:34:44 PM'. An Access table will allow you to insert the time value without adding the '1/1/1900' date value. Can this be done in SQL7?

Thanks for any help.

View 1 Replies View Related

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 View Related

DateTime.Min Won't Insert Into SQL Server Mobile 3.0

Jul 7, 2006

Hi all,

In my C# code I have a Class property that takes the value DateTime.Min upon initialisation, but when I try to insert this into the database column (yes, it is DateTime data type :)) I get an 'Unexpected Error' from SQL Server Mobile.

Is this a known?

Tryst

View 3 Replies View Related

Transact SQL :: Insert Into With Cast Datetime

Aug 10, 2015

I am trying to automate a load of insert cmd but some of them contain date times so i am trying to insert the following but keep getting

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

What is wrong with the cmd??

INSERT INTO client VALUES (100, NULL, NULL, NULL, NULL, 1, NULL, 0, 0, 0, 0, 0, NULL,Cast( '2013-03-11 10:54:46.529' as datetime))

View 11 Replies View Related

Insert Statement Which Uses A Return Value From An SP As An Insert Value

Jul 20, 2005

I'm quite stuck with this:I have an import table called ReferenceMatchingImport which containsdata that has been sucked from a data submission. The contents ofthis table have to be imported into another table ExternalReferencewhich has various foreign keys.This is simple but one of these keys says that the value inExternalReference.CompanyRef must be in the CompanyReference table.Of course if this is an initial import then it will not be so as partof my script I must insert a new row into CompanyReference andpopulate ExternalReference.CompanyRef with the identity column of thistable.I thought a good idea would be to use an SP which inserts a new rowand returns @@Identity as the value to insert. However this doesn'twork as far as I can tell. Is there a approved way to perform thissort of opperation? My code is below.Thanks.ALTER PROCEDURE SP00ReferenceMatchingImportAS/*Just some integrity checking going on here*/INSERT ExternalReference(ExternalSourceRef,AssetGroupRef,CompanyUnitRef,EntityTypeCode,CompanyRef, --this is the unknown ref which is returned by the spExternalReferenceTypeCode,ExternalReferenceCompanyReferenceMapTypeCode,StartDate,EndDate,LastUpdateBy,LastUpdateDate)SELECT rmi.ExternalDataSourcePropertyRef,rmi.AssetGroup,rmi.CompanyUnit,rmi.EntityType,SP01InsertIPDReference rmi.EntityType, --here I'm trying to run thesp so that I can use the return value as the insert value1,1,GETDATE(),GETDATE(),'RefMatch',GETDATE()FROM ReferenceMatchingImport rmiWHERE rmi.ExternalDataSourcePropertyRef NOT IN (SELECT ExternalSourceRefFROM ExternalReference)

View 3 Replies View Related

Insert Datetime.now && Membership Username In SqlDataSource

Feb 2, 2006

How do i insert the following information(Membership Username & Date Time) to my insert command in a SQLDatasource?<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DMC_dbconn %>"        DeleteCommand="DELETE FROM [comment] WHERE [commentno] = @commentno" InsertCommand="INSERT INTO [comment] ([customerno], [comment], [commentdate], [category]) VALUES (Membership.GetUser, @comment, DateTime.Now, @category)"        SelectCommand="SELECT * FROM [comment]" UpdateCommand="UPDATE [comment] SET [customerno] = @customerno, [comment] = @comment, [commentdate] = @commentdate, [category] = @category WHERE [commentno] = @commentno">

View 5 Replies View Related







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