Inserting NULL Into Datetime Field

Aug 17, 2007

I have a datetime field in a database which I am programmatically inserting values into. The field can be null or not null. However, I am having problems inserting NULL as part of my SQLCommand.
The value is pulled from a text box (linked to a calendar extender) and when I select a value it is being inserted fine. If I just leave the box blank though, I want the field to be set to NULL. I have tried adding in ,DBNULL.Value, as part of my VALUES(…) string, but this throws an exception. I Have tried just inserting ‘’ but that also throws an exception (“The conversion of a char data type to a datetime data type resulted in an out-of-range datetime valueâ€?), so I don’t know how I can insert this value when the field is blank? 
Can anyone shed some light please? Thanks

 

View 2 Replies


ADVERTISEMENT

Help Inserting Into Datetime Field

Feb 7, 2007

I keep getting the following error message but I don't see what's wrong with my code

Server Error in '/Admin' Application.


Arithmetic overflow error converting expression to data type datetime.The statement has been terminated.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Arithmetic overflow error converting expression to data type datetime.The statement has been terminated.Source Error:



Line 147:cmdSql.Parameters.Add("@event_active","1")
Line 148:
Line 149:cmdSql.ExecuteNonQuery()
Line 150:
Line 151:pnlForm.Visible = FalseSource File: c:hostingwebhost4lifememberNYACOAadmincalendar.aspx    Line: 149 Stack Trace:



[SqlException (0x80131904): Arithmetic overflow error converting expression to data type datetime.
The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +857466
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +735078
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1838
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +149
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +886
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +415
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135
ASP.calendar_aspx.SubmitForm(Object s, EventArgs E) in c:hostingwebhost4lifememberNYACOAadmincalendar.aspx:149
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102



Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210
  1 <%@ Register TagPrefix="cc1" Namespace="ManyMonkeys.Web.HtmlEditorLibrary.Controls" Assembly="HtmlEditorLibrary" %>
2 <%@ Page Language="VB" masterpagefile="nyacoaadmin.master" debug="true" %>
3 <%@ mastertype virtualpath="nyacoaadmin.master" %>
4 <%@ import Namespace="System" %>
5 <%@ import Namespace="System.Data" %>
6 <%@ import Namespace="System.Data.SqlClient" %>
7 <script runat="server">
8
9 Dim Connection As SqlConnection
10 Dim Sql As String
11 Dim cmdSql As SqlCommand
12 Dim dtr As SqlDataReader
13
14 Sub Page_Load
15
16 Connection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
17 Connection.Open()
18
19 If Not isPostback then
20
21 Sql = "SELECT chapter_id, chapter_name FROM chapter ORDER BY chapter_id"
22 cmdSql = New SqlCommand (Sql, Connection)
23 dtr = cmdSql.ExecuteReader()
24
25 ddlChapter.DataSource = dtr
26 ddlChapter.DataTextField = "chapter_name"
27 ddlChapter.DataValueField = "chapter_name"
28 ddlChapter.DataBind()
29
30 dtr.Close
31
32 ddlChapter.Items.Insert(0, New ListItem(" ", ""))
33
34 Call ShowList()
35
36 End If
37
38 End Sub
39
40 Sub Page_Unload
41
42 'Connection.Close()
43
44 End Sub
45
46 Sub ShowList()
47
48 Sql = "SELECT event_id, event_name, event_date, chapter_name FROM event WHERE event_active = '1' ORDER BY event_id"
49 cmdSql = New SqlCommand(sql, Connection)
50 dtr = cmdSql.ExecuteReader()
51
52 dgrdList.DataSource = dtr
53 dgrdList.DataBind()
54 dtr.Close()
55
56 pnlList.Visible = True
57
58 End Sub
59
60 Sub dgrdList_ItemCommand(s As Object, E As DataGridCommandEventArgs)
61
62 If e.CommandName = "edit" then
63 Call EditForm(dgrdList.DataKeys(e.Item.ItemIndex))
64 Else If e.CommandName = "delete" then
65 Call ConfirmDelete(dgrdList.DataKeys(e.Item.ItemIndex))
66 End If
67
68 End Sub
69
70 Sub ConfirmDelete(idVal As Integer)
71
72 pnlList.Visible = False
73 pnlConfirmDelete.Visible = True
74
75 sql = "SELECT event_name FROM event WHERE event_id = " & idVal
76 cmdSql = New SqlCommand(sql, connection)
77 litDelete.Text = cmdSql.ExecuteScalar()
78
79 ViewState("idVal") = idVal
80
81 End Sub
82
83 Sub DeleteForm (s As Object, E As Eventargs)
84
85 sql = "UPDATE event SET event_active = '0' WHERE event_id = " & ViewState("idVal")
86 cmdSql = New SqlCommand(sql, connection)
87 cmdSql.ExecuteNonQuery()
88
89 pnlList.Visible = True
90 pnlConfirmDelete.Visible = False
91
92 Call ShowList()
93
94 End Sub
95
96 Sub ShowCalendar(s As Object, E As ImageClickEventargs)
97
98 pnlEventDate.Visible = True
99
100 End Sub
101
102 Sub UpdateDate (s As Object, E As Eventargs)
103
104 pnlEventDate.Visible = False
105 txtEventDate.text=eventCalendar.SelectedDate.ToShortDateString()
106
107 End Sub
108
109 Sub SubmitForm (s As Object, E As Eventargs)
110
111 If ViewState("submitType") = "edit" then
112 sql = "UPDATE event SET event_name=@event_name, event_date=@event_date, chapter_name=@chapter_name, event_description=@event_description, event_last_updated_by=@event_last_updated_by, event_active=@event_active WHERE event_id = " & ViewState("idVal")
113 Else
114 sql = "INSERT INTO event (event_name, event_date, chapter_name, event_description, event_added_by, event_last_updated_by, event_active) VALUES (@event_name, @event_date, @chapter_name, @event_description, @event_added_by, @event_last_updated_by, @event_active)"
115 End If
116
117 cmdSql = New SqlCommand(sql, Connection)
118
119 If Len(txtEventName.Text) = 0 then
120 cmdSql.Parameters.Add("@event_name",DbNull.Value)
121 Else
122 cmdSql.Parameters.Add("@event_name",txtEventName.Text)
123 End If
124
125 If Len(txtEventDate.Text) = 0 then
126 cmdSql.Parameters.Add("@event_date",DbNull.Value)
127 Else
128 cmdSql.Parameters.Add("@event_date",txtEventDate.Text & " " & ddlEventHour.SelectedValue & ":" & ddlEventMinute.SelectedValue & " " & ddlEventAMPM.SelectedValue)
129 End If
130
131 If Len(ddlChapter.SelectedValue) = 0 then
132 cmdSql.Parameters.Add("@chapter_name",DbNull.Value)
133 Else
134 cmdSql.Parameters.Add("@chapter_name",ddlChapter.SelectedValue)
135 End If
136
137 If Len(txtEventDescription.Text) = 0 then
138 cmdSql.Parameters.Add("@event_description",DbNull.Value)
139 Else
140 cmdSql.Parameters.Add("@event_description",txtEventDescription.Text)
141 End If
142
143 cmdSql.Parameters.Add("@event_added_by",session("admin_username"))
144
145 cmdSql.Parameters.Add("@event_last_updated_by",session("admin_username"))
146
147 cmdSql.Parameters.Add("@event_active","1")
148
149 cmdSql.ExecuteNonQuery()
150
151 pnlForm.Visible = False
152 pnlList.Visible = True
153
154 Call ShowList()
155
156 End Sub
157
158 Sub AddForm(s As Object, E As Eventargs)
159
160 pnlForm.Visible = True
161 pnlList.Visible = False
162
163 txtEventName.Text = ""
164 txtEventDate.Text = ""
165 ddlChapter.ClearSelection()
166 txtEventDescription.Text = ""
167
168 ViewState("submitType") = "add"
169
170 End Sub
171
172 Sub EditForm (idVal As Integer)
173
174 pnlList.Visible = False
175 pnlForm.Visible = True
176
177 sql = "SELECT * FROM event WHERE event_id = " & idVal
178 cmdSql = New SqlCommand(sql, connection)
179 dtr = cmdSql.ExecuteReader()
180
181 If dtr.Read() then
182
183 txtEventName.Text = dtr("event_name") & ""
184 txtEventDate.Text = dtr("event_date") & ""
185 txtEventDescription.Text = dtr("event_description") & ""
186 ddlChapter.ClearSelection()
187 Try
188 ddlChapter.Items.FindByValue(dtr("chapter_name")).Selected = True
189 Catch Ex As Exception
190 End Try
191
192 End If
193
194 dtr.Close()
195
196 ViewState("submitType") = "edit"
197 ViewState("idVal") = idVal
198
199 End Sub
200
201 Sub DeleteCancel (s As Object, E As Eventargs)
202
203 pnlConfirmDelete.Visible = False
204 pnlList.Visible = True
205
206 End Sub
207
208 </script>
209
210 <asp:Content contentplaceholderid="cplhMainContent" runat="server">
211
212 <asp:Panel runat="server" id="pnlList" Visible="False">
213
214 <asp:DataGrid runat="server" id="dgrdList" AutoGenerateColumns="False" CellPadding="3" CellSpacing="0" width="550" Border="0" DataKeyField="event_id" onItemCommand="dgrdList_ItemCommand">
215 <HeaderStyle BackColor="#CDAD00" Font-Names="Tahoma,Arial,Helvetica,sans-serif" Font-Bold="true" Font-Size="10pt" HorizontalAlign="center" ForeColor="white" />
216 <ItemStyle BackColor="white" Font-Names="Tahoma,Arial,Helvetica,sans-serif" Font-Size="10pt" ForeColor="black" VerticalAlign="top" />
217 <AlternatingItemStyle BackColor="#dcdcdc" Font-Names="Tahoma,Arial,Helvetica,sans-serif" Font-Size="10pt" ForeColor="black" VerticalAlign="top" />
218 <Columns>
219 <asp:ButtonColumn Text="Edit" ButtonType="PushButton" CommandName="edit" />
220 <asp:ButtonColumn Text="Delete" ButtonType="PushButton" CommandName="delete" />
221 <asp:BoundColumn DataField="event_name" HeaderText="Event Name" />
222 <asp:BoundColumn DataField="event_date" HeaderText="Date" />
223 <asp:BoundColumn DataField="chapter_name" HeaderText="Sponsoring Chapter" />
224 </Columns>
225 </asp:DataGrid>
226
227 <asp:Button runat="server" Text="Add New Event" onClick="AddForm"></asp:Button>
228
229 </asp:Panel>
230
231 <asp:Panel runat="server" id="pnlForm" Visible="False">
232
233 Name of Event: <asp:TextBox id="txtEventName" runat="server"></asp:TextBox>
234 <br />Chapter: <asp:DropDownList id="ddlChapter" runat="server" AutoPostBack="False" />
235 <br />Date: <asp:TextBox id="txtEventDate" runat="server" ReadOnly="true" BackColor="Gray"></asp:TextBox> <asp:ImageButton id="CalButton" runat="server" OnClick="ShowCalendar" ImageUrl="images/cal.gif" />
236 <br /><asp:Panel runat="server" id="pnlEventDate" Visible="False">
237 <asp:Calendar id="eventCalendar" runat="server" FirstDayOfWeek="Sunday" Font-Names="Tahoma" Font-Size="8pt" OnSelectionChanged="UpdateDate">
238 <SelectedDayStyle BackColor="#EC9900" Font-Bold="True" />
239 <TodayDayStyle BackColor="#FFC0C0" />
240 <SelectorStyle Font-Names="Tahoma" Font-Size="8pt" />
241 <DayStyle Font-Names="Tahoma" Font-Size="8pt" />
242 <WeekendDayStyle BackColor="#E0E0E0" />
243 <OtherMonthDayStyle ForeColor="Silver" />
244 <DayHeaderStyle BackColor="#334B79" Font-Names="Tahoma" Font-Size="8pt" ForeColor="White" />
245 <TitleStyle BackColor="#CCCCFF" Font-Bold="True" Font-Names="Tahoma" Font-Size="10pt" />
246 </asp:Calendar>
247 <br />
248 </asp:Panel>
249 Time: <asp:DropDownList ID="ddlEventHour" runat="server" >
250 <asp:ListItem Text="12" Value="12" Selected="true"/>
251 <asp:ListItem Text="1" Value="1" />
252 <asp:ListItem Text="2" Value="2" />
253 <asp:ListItem Text="3" Value="3" />
254 <asp:ListItem Text="4" Value="4" />
255 <asp:ListItem Text="5" Value="5" />
256 <asp:ListItem Text="6" Value="6" />
257 <asp:ListItem Text="7" Value="7" />
258 <asp:ListItem Text="8" Value="8" />
259 <asp:ListItem Text="9" Value="9" />
260 <asp:ListItem Text="10" Value="10" />
261 <asp:ListItem Text="11" Value="11" />
262 </asp:DropDownList>
263 :
264 <asp:DropDownList ID="ddlEventMinute" runat="server">
265 <asp:ListItem Text="00" Value="00" Selected="true" />
266 <asp:ListItem Text="15" Value="15" />
267 <asp:ListItem Text="30" Value="30" />
268 <asp:ListItem Text="45" Value="45" />
269 </asp:DropDownList>
270 <asp:DropDownList ID="ddlEventAMPM" runat="server">
271 <asp:ListItem Text="AM" Value="AM" />
272 <asp:ListItem Text="PM" Value="PM" Selected="true" />
273 </asp:DropDownList>
274 <br /><br />
275 Content:
276 <br /><cc1:HtmlEditor id="txtEventDescription" runat="server" Height="300px" Width="575px"></cc1:HtmlEditor>
277 <br /><br />
278 <asp:Button onclick="SubmitForm" runat="server" Text="Submit"></asp:Button>
279
280 </asp:Panel>
281
282 <asp:Panel runat="server" id="pnlConfirmDelete" Visible="False">
283
284 Are you sure you wish to delete <asp:Literal runat="server" id="litDelete"></asp:Literal>?
285 <br /><br />
286 <asp:Button runat="server" Text="Yes - DELETE" onClick="DeleteForm"></asp:Button>&nbsp;<asp:Button runat="server" Text="No - GO BACK" onClick="DeleteCancel"></asp:Button>
287
288 </asp:Panel>
289
290 </asp:Content>
 

View 4 Replies View Related

Problem Inserting Now() Into A Datetime Field

Mar 22, 2006

HiI am trying to insert value retrieved from Now() into a datetime field in my MSDE database, but I am getting the following error, and I have no idea what is going wrong.Arithmetic overflow error converting expression to data type datetime.The statement has been terminated.Here is the code I am using:Dim user As String = MyContext.User.Identity.Name.ToString
Dim TimeDate As DateTime = Now()
Dim status As String = "Pending"

With SqlOrders.InsertParameters
.Item("UserName").DefaultValue = user
.Item("OrderDate").DefaultValue = TimeDate
.Item("Status").DefaultValue = status
End With
SqlOrders.Insert()The date is being returned in this format 23/03/2006 02:01:52, which is the same format as it should appear in the database. could anyone please tell me where I am going wrong?

View 2 Replies View Related

Problem With Inserting Date In A Datetime Field

Apr 24, 2004

Hi, I have a problem when I insert a date in a datetime field in a MSSQLServer.
That's my problem:
if the server is in english version, I have to insert date with this code:

DateTime.Today.ToString("MM/dd/yyyy")

instead if the server is in italian version, I have to insert date with this code:

DateTime.Today.ToString("dd/MM/yyyy")

Is there a way to insert a date in standard way, without knowing the server version?

bye and thanks in advance

View 3 Replies View Related

Manually Inserting Data In DateTime Field

Oct 2, 2006

Using Server Explorer in VB 2005, I am manually entering data in a table in a SQL Server 2005 Express database that includes a DateTime field. I have tried every conceivable format, but no matter what I try get one of these 2 errors:

1. String was not recognized as valid DateTime

2. Operand type class; text incompatible with DateTime

I have Googled this to death, but no example which involves trying to enter the data manually, say from Server Explorer.

Formats tried include all datetime formats (mmddyy, yymmdd, using dashes or slashes, enclosing in single quotes or pound signs).

I would appreciate if someone could please give me an example that I can literally insert without error.

View 4 Replies View Related

INSTEAD OF Trigger - Error Inserting Into NOT NULL Field

Oct 7, 2004

I've just noticed some strange behavior that seems like a bug to me.
It's much easier to follow an example of it that to outright explain it, so here goes.

I have a table defined with a NOT NULL constraint on a column and a default clause:
-- DROP TABLE TestTable
CREATE TABLE TestTable ( TestField0 varchar(10), TestField1 varchar(10) NOT NULL DEFAULT ('a') )

I have a view defined on the table, in this example case, the view just mirrors the table one to one:
-- DROP VIEW TestView
CREATE VIEW TestView as SELECT TestField0, TestField1 FROM TestTable

So far so good, if I run this statement, it works as I would expect and inserts the value and the default goes into the other field:
INSERT INTO TestView (TestField0) SELECT 'test'

Now... If I add an INSTEAD OF trigger to the view, and have it perform the insert for me, I get an error with the same insert stmt:
-- DROP TRIGGER TestTrigger
CREATE TRIGGER TestTrigger ON TestView
INSTEAD OF INSERT AS
BEGIN
INSERT INTO TestTable (TestField0, TestField1)
SELECT TestField0, COALESCE(TestField1, 'X')
FROM inserted
END

Notice the trigger will ensure that a null value cannot be inserted into TestField1. If I run this insert stmt though I get an error:
INSERT INTO TestView (TestField0) SELECT 'test'

Server: Msg 233, Level 16, State 2, Line 1
The column 'TestField1' in table 'TestView' cannot be null.


Am I missing something or is this a bug?
Thanks

View 1 Replies View Related

Inserting And Retriving Datetime Field In Database MSSQL 2000

Jan 10, 2006

Hi, Assume I have a table name "myTime". This table is simply only have 1 (one) DATETIME field "MyTestTime" (also serve as a primary number).Table MyTime- MyTestTime : SQLTYPE DATETIMETo insert a new row into this field, I simply wrote :SqlCommand sqlCommand = new SqlCommand("insert into MyTime values('2006-01-09')", sqlConnection);
I got the value of "2006-01-09" from a textbox or other relevan control.I realize when I try to use "SELECT * FROM MyTime" statement, MSSQL server 2000 automatically convert my date value from "2006-01-09" to "01/09/2006" (from YYYY-MM-DD to MM/DD/YYYY). I don't know why this one must be converted to MM/DD/YYYY automatically (I believe this behavior is depend on some "setting option" in my MSSQL server - but I don't know which one).The challenge is :In my country, the actual date format is like German Date format (DD-MM-YYY). Well I know this is only "Customization" problem. But how insert datetime value given from sql query to a datetime variable?// Connect to database, make a query, get the datareader result, and bla bla blaDateTime aDateTime = new DateTime;aDateTime = Convert.ToDateTime(myDataReader["PostDate"].ToString());// close connectionMy question isHow can I make sure that aDateTime's day is 09 not 01. How my program know that 09 is day not month. I can't use string.split() method because it's possible that my database setting will change from "mm-dd-yyyy" to "dd-mm-yyyy"thanks

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

Null Datetime Field Contains 1-Jan-1900

Feb 10, 1999

I have defined fields in a table as datetime fields and allow nulls. SQL 6.5 is placing 1-Jan-1900 in all of these fields causing me to have to filter out these dates when retrieving a recordset.
How do I get rid of this?


thanks!

View 1 Replies View Related

Sql SELECT Returning NULL On DateTime Field

Aug 8, 2006

Hi there ;
This Problem is goin to make me crazy!
I've got a table with couple of fields, 2 of them are DateTime, in Sql Express 05 .
I used asp.net 2.0 to insert datetime values, directly,  using sth like DateTime.Now.ToString() .
i use 2 selects as follows :
1)select * from X where  Date1='8/9/2006 11:17:41 AM'
2)select * from X where  Date2='8/9/2006 11:17:41 AM'
#1 is OK, but the second one returns a row with all columns set to NULL .
(X is the name of the table)
Thanks in advance

View 6 Replies View Related

How To Replace DateTime Field With Null Value In SQL 2005 Server

Apr 7, 2006

How to replace DateTime field with null value in SQL 2005 server
I create a stored procedure aa, It works well, but sometimes I hope to replace CreateDate field with null value,I don't know how to doIt seems that datetime type is not null value
create aa  @CreateDate DatetimeAsUpdate cw set CreateDate=@CreateDate
 
 

View 3 Replies View Related

Mssql Won't Find NULL Values In Datetime Field??

Feb 13, 2007

Hi

I have a really simple query which i can't figure out why its not working. I have a table called 'ADMIN' which has a datetime field called 'date_edited'. Because the majority of records have never been edited, i have allowed null values and they are filled with 'NULL' in each record. How ever, when i try:

SELECT * FROM ADMIN WHERE date_edited = NULL

I get no records, but i can see and know i have hundreds! I know i'm doing somthing really stupid, but for life of me can't figure it out! :eek:

thanks

View 10 Replies View Related

Conditional Execution With Null Checking For DateTime Field

Mar 11, 2008

There was a similar question to mine a few time ago about conditional execution, but I'm having some problems with it to which I couldn't find any answer, could anyone help?

My condition is checking if a DateTime from a DB table is null. I use the Execute SQL Task to retrieve the record (SELECT TOP 1 * FROM myTable WHERE conditions = TRUE), then I map 2 fields to their respective global variables.

Then I created the green arrow connector and used a precedence expression based on sucess. I used the expression IsNull(@variable). For some reason, even if the @variable comes as null - I checked the info in the DB - it still comes out as '1999-11-30'

I've looked around and the IsNull method can be used to also change the value in the event of it being null, could it be changing my variables value to this even if I didn't pass that value as a parameter to the function? If so, how else can I test it for null? I've tried "== null", "= null" and even ".equals(null)" - which I know is absurd, but I'm running out of options here...

Could you enlighten me, please???
Thanks in advance!

View 4 Replies View Related

DateTime.Now, An Allowed Null Field, And My Insert Function From My Dataset

Jun 6, 2008

I have a table adapter for one of my SQL2005 tables, and in two different fields I accept a date time. Now 99% of the times, new rows to this table will be filled out using DateTIme.Now(), as a Time Stamp is what I'm going for.
 
Here is the line of code in question...cops_current_data_adapter.Insert(ProductOrder, Convert.ToInt16(Session["StationId"].ToString()),
PartNumber, DateTime.Now, DateTime.Now, Convert.ToInt16(qty), 0);
 The second DateTime.Now is the one that can be null, and it's throwing a formatting error everytime I try and drop it in there. It's a FormatException, and there's not much more to the example except unhelpful tips like be careful when conveting a string to a dateTime, which I'm not doing. Needless to say for the code to compile, and then throw a Format error at runtime is a bit frustraiting.
 Any suggestions would be most appreciated

View 1 Replies View Related

Seeking Correct Syntax To Pass A NULL Value For A Datetime Field From An Asp Page To SQL

Jan 13, 2006

Hello,I've been searching the web for quite some time to resolve the problemof "1/1/1900" returning in a datetime field in SQL that resulted from ablank (not NULL) value being passed to it through an ASP page.The solution is that a NULL value needs to passed to SQL from ASP.Thats fine...I understand the why the problem is happening and thesolution around it. HOWEVER, I can't seem to get the proper syntax towork in the ASP page. It seems no matter what I try the "1/1/1900"still results. Below are a few variations of the code that I havetried, with the key part being the first section. Does anyone have anysuggestions?!?!?______________cDateClosed = ""If(Request.Form("dateClosed")= "") ThencDateClosed = (NULL)end ifsql="UPDATE rfa SET "&_"dateClosed='"& cDateClosed &"', "&_"where rfaId='"& Request.Form("RFAID")&"'"_____________________________cDateClosed = ""If(Request.Form("dateClosed") <> "") ThencDateClosed = (NULL)end ifsql="UPDATE rfa SET "&_"dateClosed='"& cDateClosed &"', "&_"where rfaId='"& Request.Form("RFAID")&"'"_____________________________cDateClosed = ""If(Request.Form("dateClosed")= "") ThencDateClosed = NULLend ifsql="UPDATE rfa SET "&_"dateClosed='"& cDateClosed &"', "&_"where rfaId='"& Request.Form("RFAID")&"'"_______________Thanks in advance!!!!

View 7 Replies View Related

Working In VB.Net 2005 Inserting NULL Into A Field In Microsoft SQL Server 2005

Feb 2, 2007

I am update/inserting records threw a web form in vb.net. I need to insert 'NULL'  into my microsoft sql server database.  I am not talking about the below line of code where website is the name of my paramater.  If i do that it will just place a blank into that field in the database.  If i dont enter anything into that textbox I want it to to say NULL in that field. So if I go into the actual table in the SQL Server Management Studio and look at the website field of the recored I just added or updated and did not type anything into the web site textbox it needs to say NULL.  I also tried the second line of code but that places a single quote in front and behind NULL. So the field will have the value 'NULL'.
website.value = txtwebsite.text.tostirng
 if txtwebsite.text ="" then
   website.value ="NULL"
end if
The reason why I need the NULL there is because I bind the website filed to a hyperlink template in a gridview.  The actual text of the hyperlink is bound to PAYER which is a name of a insurance payer but the navigateto is bound to the website field.  If i do not enter any data into the website field and it stays as NULL, then when my gridview is loaded, payers that dont have a website will not be underlined and user wont have the option to click on them since there is no value for the navigateto.  But if i use my form to update/add a payer and leave the website textbox blank in puts a blank into that field in my database and when it loads that new row into the gridview the PAYER is underlined and u can click on it but it will just take u to the web site is unavailable page.  So is there anyway to actaull have NULL placed into a filed and not just blank space

View 3 Replies View Related

Millisecond Values Missing When Inserting Datetime Into Datetime Column Of Sql Server

Jul 9, 2007

Hi,
I'm inserting a datetime values into sql server 2000 from c#

SQL server table details
Table nameate_test
columnname datatype
No int
date_t DateTime

C# coding
SqlConnection connectionToDatabase = new SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=testdb;Integrated Security=SSPI");
connectionToDatabase.Open();
DataTable dt1 = new DataTable();
dt1.Columns.Add("no",typeof(System.Int16));
dt1.Columns.Add("date_t", typeof(System.DateTime));
DataRow dr = dt1.NewRow();
dr["no"] = 1;
dr["date_t"] = DateTime.Now;
dt1.Rows.Add(dr);
for(int i=0;i<dt1.Rows.Count;i++)
{
string str=dt1.Rows["no"].ToString();
DateTime dt=(DateTime)dt1.Rows["date_t"];
string insertQuery = "insert into date_test values(" + str + ",'" + dt + "')";
SqlCommand cmd = new SqlCommand(insertQuery, connectionToDatabase);
cmd.ExecuteNonQuery();
MessageBox.Show("saved");
}
When I run the above code, data is inserted into the table
The value in the date_t column is 2007-07-09 22:10:11 000.The milliseconds value is always 000 only.I need the millisecond values also in date_t column.
Is there any conversion needed for millisecond values?

thanks,
Mani

View 3 Replies View Related

Inserting Datetime Through Sqldatasource - String Was Not Recognized As A Valid DateTime

Dec 6, 2006

I'm getting error:
String was not recognized as a valid DateTime.
my insert parameter: 
<asp:Parameter Name="LastModified" Type="DateTime" DefaultValue= "<%=DateTime.Now.ToString() %>"
my insert command:
InsertCommand="INSERT INTO [Product] ([Enabled], [ProductCode], [ProductName], [ProductAlias], [CarrierId], [DfltPlanId], [DoubleRating], [DoubleRateProductId], [ConnCharges], [StartDate], [EndDate], [Contracted], [BaseProductId], [LastModified], [LastUser]) VALUES (@Enabled, @ProductCode, @ProductName, @ProductAlias, @CarrierId, @DfltPlanId, @DoubleRating, @DoubleRateProductId, @ConnCharges, @StartDate, @EndDate, @Contracted, @BaseProductId, @LastModified, @LastUser)"
LastModified is a datetime field.
 Running sql2005

View 1 Replies View Related

DateTime Unable To Save In Datetime Field Of SQL Database

Mar 14, 2007

 Hi all, having a little problem with saving dates to sql databaseI've got the CreatedOn field in the table set to datetime type, but every time i try and run it i get an error kicked up  Error "The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.The statement has been terminated."I've tried researching it but not been able to find something similar.  Heres the code: DateTime createOn = DateTime.Now;string sSQLStatement = "INSERT INTO Index (Name, Description, Creator,CreatedOn) values ('" + name + "','" + description + "','" + userName + "','" + createOn + "')"; Any help would be much appreciated 

View 4 Replies View Related

How To Add Date Field And Time Field (not Datetime Field )

May 4, 2006

Good morning...

I begin with SQL, I would like to add a field that will be date like 21/01/2000.

Actually i find just "datetime" format but give me the format 21/01/2000 01:01:20.

How to do for having date and time in two different field.

Sorry for my english....

Cordially

A newbie

View 3 Replies View Related

How To Convert Datetime Field To A Date Field So Excel Recognize It As Data Type

May 17, 2015

I embedded a SQL query in excel that gets some datetime fields like "TASK_FINISH_DATE" .

How can I convert a datetime field to a date field in SQL in a way that excel will recognize it as a date type and not a text type?

I tried:
CONVERT(varchar(8),TASK_FINISH_DATE ,3)
CONVERT(Date,TASK_FINISH_DATE ,3)
CAST(TASK_FINISH_DATE as date)

**all of the above returned text objectes in excel and not date objects.

View 3 Replies View Related

Informix Date Type Field To SQL Server Datetime Field Error

Oct 17, 2007



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.

What options do I have that will work?

View 1 Replies View Related

Converting Datetimeoffset Field To Datetime Field / Why Milliseconds Value Is Incorrect

Nov 17, 2012

DECLARE @datetimeoffset datetimeoffset(3)
DECLARE @datetime datetime
SELECT @datetimeoffset = '2012-11-08T17:22:13.575+00:00'
SELECT @datetime = @datetimeoffset
SELECT @datetimeoffset AS '@datetimeoffset ', @datetime AS 'datetime'
__________________________________________________ ___________
Result of above SQL is
@datetimeoffset datetime
2012-11-08 17:22:13.575 +00:002012-11-08 17:22:13.577
__________________________________________________ ____________

The result should be '2012-11-08 17:22:13.575', why the milliseconds value is incorrect

View 2 Replies View Related

Pass In Null/blank Value In The Date Field Or Declare The Field As String And Convert

Dec 30, 2003

I need to pass in null/blank value in the date field or declare the field as string and convert date back to string.

I tried the 2nd option but I am having trouble converting the two digits of the recordset (rs_get_msp_info(2), 1, 2))) into a four digit yr. But it will only the yr in two digits.
The mfg_start_date is delcared as a string variable

mfg_start_date = CStr(CDate(Mid(rs_get_msp_info(2), 3, 2) & "/" & Mid(rs_get_msp_info(2), 5, 2) & "/" & Mid(rs_get_msp_info(2), 1, 2)))

option 1
I will have to declare the mfg_start_date as date but I need to send in a blank value for this variable in the stored procedure. It won't accept a null or blank value.

With refresh_shipping_sched
.ActiveConnection = CurrentProject.Connection
.CommandText = "spRefresh_shipping_sched"
.CommandType = adCmdStoredProc
.Parameters.Append .CreateParameter("ret_val", adInteger, adParamReturnValue)
.Parameters.Append .CreateParameter("@option", adInteger, adParamInput, 4, update_option)
.Parameters.Append .CreateParameter("@mfg_ord_num", adChar, adParamInput, mfg_ord_num_length, "")
.Parameters.Append .CreateParameter("@mfg_start_date", adChar, adParamInput, 10, "")
Set rs_refresh_shipping_sched = .Execute
End

Please help

View 6 Replies View Related

Inserting A Null Value

Dec 5, 2003

Hello,

I have got a database with a datetime field. I insert a date into the database from a textbox. All is fine if someone enters a date. If someone enters nothing I want a null to be inserted. How do I do this?

Grant

View 1 Replies View Related

Inserting “&<NULL&>”

Oct 13, 2005

how do you write an insert into statement and keep “<NULL>” in the null cells?

i was trying something like this BUT when you try to write an IS NULL statement it doesnt work.


ISNULL(dbo.TRUNK02_LastVersion_PayableClaims_01.MO D1, NULL) AS Mod1,

View 4 Replies View Related

Inserting Null Value

Sep 19, 2005

Is there a way, I can insert NULL value to "DT_Date" type Row Column using Script Component Transformation of Data flow?

View 8 Replies View Related

Datetime To Dd/MM/yyyy For Inserting Into DB

Jul 1, 2007

hi there, i have a calendar that i put into a string ilke this
string str = Calendar1.SelectedDate.ToShortDateString();
the result is dd/mm/yyyy date which is great, but for inserting into my DB (MSSQL) it needs to be a datetime field, however when i convert it
Datetime dtDate = Convert.ToDateTime(str);
it takes my date and adds 00:00:00 onto the end and this is not what i want! i just want the dd/mm/yyy how do i do this, it has to be simple but i have been searching for hours and cant find anything, i am using ASP.NET 2 and C#
Thanks

View 3 Replies View Related

Inserting Null Into A Record

Sep 8, 2007

I am simply trying to use SQLCommand in .net to insert a record into a SQL Server 2005 table. There are 2 fields being pulled from a user input for that could have no values selected. In this case I want to insert a null value into the record. I get an error that Null is no longer supported and that I should use System.DBNull, but that can't be used as an expression.
 How do I do this?
Thank you in advance.

View 1 Replies View Related

Inserting Null Values

May 11, 2004

Hi,

I am trying to insert null values into sql server from my access from. I am using sql statement. But it says 'Syntex error in Insert statement'. When i remove null values it works fine? How can I insert null values into a table?

Any help will be highly appreciated.

View 3 Replies View Related

INSERTing A String Containing NULL () From PHP App

Jul 1, 2006

Folks, this isn't exactly a 'Getting Started' question, but I couldn't find a more appropriate Application Development forum.

I'm porting an open source PHP application (http://sourceforge.net/projects/gallery) to use SQL Server as a backend. One of Gallery's unit test scripts tests the ability to insert a string containing a NULL character (). It's OK if the string is truncated during insertion, just so long as everything before the is there.

The string being inserted looks like:




$testString = "The NULL character should be escaped !";



(Note the between "escaped " and " !")

The error that the Gallery test script is getting is:




[Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'The NULL character should be escaped '.] in EXECUTE("INSERT INTO g2_PluginParameterMap (g_pluginType, g_pluginId, g_itemId, g_parameterName, g_parameterValue) VALUES ('module','unitTestModule',1,'test19476','The NULL character should be escaped !')")



It looks like SQL Server is complaining about the syntax. I've written a much simpler test script in the hopes of reproducing the problem, but I don't know if what I'm now hitting is the same problem or a different one.

My simple script is:




<?php

$localhost = exec("hostname");
$database = "gallery2";
$uid = "g2user";
$pwd = "g2pwd";
$connectString = "Host=PROVIDER=MSDASQL;DRIVER={SQL Server};";
$connectString .= "SERVER=$localhost\sqlexpress;";
$connectString .= "DATABASE=$database;";
$connectString .= "UID=$uid;PWD=$pwd";

$sqlTableDrop = "drop table ljmtemp";
$sqlTableCreate = "create table ljmtemp (col1 nvarchar(100))";
$sqlTableQuery = "select len(col1) from ljmtemp";

// Connect to the db
$db = new COM("ADODB.Connection") or die("Cannot start ADO");
$db->open($connectString);

// Drop & recreate the table
$db->Execute ($sqlTableDrop);
$db->Execute ($sqlTableCreate);

// Insert the test data
//$testString = "The NULL character should be escaped !";
$testString = "This is a test string.";
$res = $db->Execute("insert into ljmtemp (col1) values ('$testString')");
if (!$res) die ("INSERT failed");

// Disconnect from the db
$db->Close();

?>



And it results in:




C:MyServer>php testMsSqlInsertNull.php
PHP Fatal error: Uncaught exception 'com_exception' with message 'Source: Microsoft OLE DB Provider for ODBC Drivers
Description: [Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark after the character string 'The NULL character should be escaped '.' in C:MyServer estMsSqlInsertNull.php:27
Stack trace:
#0 C:MyServer estMsSqlInsertNull.php(27): com->Execute('insert into ljm...')
#1 {main}
thrown in C:MyServer estMsSqlInsertNull.php on line 27



I'm not sure if this is the same problem as Gallery is reporting or another one.

It looks like somebody is treating the as a string terminator, but when i double the backslash the literal '' is inserted into the database.

How can I get SQL Server to insert at least everything up to the ?

Hopefully once I have my simple script working I'll be able to figure out what's wrong in the Gallery test.

Thanks.

View 10 Replies View Related

Inserting Datetime In Microsoft SQL Database

Dec 29, 2004

Hi,
I am working with "sql server enterprise manager".
How can I insert datetime(i.e. date) value in the datetime column in my database using an sql command?

Eg.
If I have a table named Table1 in my database, and this table is composed of one primary key column and one datetime column (named dateofreceipt), how should the syntax look like?

Thank you
Vuchko

View 2 Replies View Related

Inserting Datetime With Milliseconds In SQL Server

Jul 20, 2005

Hello all.I am attempting to insert a row into a table with a datetime column:When the insert statement contains a value for the millisecond portionof the data time column: ie. {ts '2003-11-05 12:02:43:2960'}I get 'Syntax error converting datetime from string'When I insert a value like: {ts '2003-11-05 12:02:43'}with no millisecond value it succeeds.Any help would be appreciated.Thanks

View 5 Replies View Related







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