Smalldatetime To String Conversion, Can't Find Error

Sep 3, 2007

Hi, I'm making a webapplication in C# with MSSQL as database.

I've created a form to do an advanced search on books. The user can type in name, author, .... and he can also mark 2 dates from to Calendar objects (I made sure date one can not be bigger than date 2). I'm using smalldatetime as DBtype. The 2 selected values are DateTime in asp. The results are shown in a gridview. Since I added the feature I keep getting the same error and I can't find where it is. Here's some code:

 1 public List GetBooks2(string invB,string titelB, string auteursB, string taalB, string uitgeverijB, string jaarB, string keywordsB, string categorieB, string standplaatsB, string ISBN,DateTime datum1, DateTime datum2, string sortExpression)
2 { //this is my method for the advanced search
3 using (SqlConnection oConn = new SqlConnection(_connectionString))
4 {
5 string strSql = "select * FROM Boek where 1 = 1";
6 if (!String.IsNullOrEmpty(invB)) strSql += " and (inventaris_nr like @invB)";
7 if (!String.IsNullOrEmpty(titelB)) strSql += " and (titel like @titelB)";
8 if (!String.IsNullOrEmpty(auteursB)) strSql += " and (auteurs like @auteursB)";
9 if (!String.IsNullOrEmpty(uitgeverijB)) strSql += " and (uitgeverij like @uitgeverijB)";
10 if (!String.IsNullOrEmpty(ISBN)) strSql += " and (ISBN10 like @ISBN or ISBN13 like @ISBN)";
11 if (!String.IsNullOrEmpty(standplaatsB)) strSql += " and (standplaats like @standplaatsB)";
12 if (!String.IsNullOrEmpty(jaarB)) strSql += " and (jaartal like @jaarB)";
13 if (!String.IsNullOrEmpty(keywordsB)) strSql += " and (keywords like @keywordsB)";
14 if (!String.IsNullOrEmpty(taalB))
15 if (taalB == "Andere")
16 strSql += " and (taal NOT IN ('nederlands', 'frans', 'engels', 'spaans', 'italiaans', 'duits'))";
17 if (taalB == "--Geen voorkeur--")
18 strSql += "";
19 else
20 strSql += " and (taal like @taalB)";
21
22 if (!String.IsNullOrEmpty(categorieB))
23 if (categorieB == "--Selecteer een categorie--")
24 strSql += "";
25 else
26 strSql += " and (categorie like @categorieB)";
27
28 if (datum1 == null)
29 strSql += "";
30 else
31 if (datum2 != null)
32 {
33
34 strSql+=" and datumB between @datum1 and @datum2";
35 }
36 else strSql+="";
37 if (!String.IsNullOrEmpty(sortBLOCKED EXPRESSION
38 strSql += " order by " + sortExpression;
39 else
40 strSql += " order by id";
41
42 SqlCommand oCmd = new SqlCommand(strSql, oConn);
43 oCmd.Parameters.Add(new SqlParameter("@invB", "%" + invB + "%"));
44 oCmd.Parameters.Add(new SqlParameter("@titelB", "%" + titelB + "%"));
45 oCmd.Parameters.Add(new SqlParameter("@auteursB", "%" + auteursB + "%"));
46 oCmd.Parameters.Add(new SqlParameter("@taalB", "%" + taalB + "%"));
47 oCmd.Parameters.Add(new SqlParameter("@uitgeverijB", "%" + uitgeverijB + "%"));
48 oCmd.Parameters.Add(new SqlParameter("@jaarB", "%" + jaarB + "%"));
49 oCmd.Parameters.Add(new SqlParameter("@keywordsB", "%" + keywordsB + "%"));
50 oCmd.Parameters.Add(new SqlParameter("@categorieB", categorieB ));
51 oCmd.Parameters.Add(new SqlParameter("@standplaatsB", "%" + standplaatsB + "%"));
52 oCmd.Parameters.Add(new SqlParameter("@ISBN", "%" + ISBN + "%"));
53 oCmd.Parameters.Add(new SqlParameter("@datum1", "%" + datum1 + "%"));
54 oCmd.Parameters.Add(new SqlParameter("@datum2", "%" + datum2 + "%"));
55
56
57 oConn.Open();
58 SqlDataReader oReader = oCmd.ExecuteReader();
59 List boeken = GetBoekCollectionFromReader(oReader);
60 oReader.Close();
61 return boeken;
62 }
63 }


 

I think that that method is correct, not sure though...  The code for GetBoekCollectionFromReader(oReader) is this=1 protected List GetBoekCollectionFromReader(IDataReader oReader)
2 {
3 List boeken= new List();
4 while (oReader.Read()) //THIS IS WHERE THE ERROR APPEARS
5 {
6 boeken.Add(GetBoekFromReader(oReader));
7
8 }
9 return boeken;
10 }
  

 

That's the method where the error appears... Where should I place a breakpoint to get the exact location? To make sure all methods in this code are explained, here's the code for GetBoekFromReader(oReader))= 1 protected Boek GetBoekFromReader(IDataRecord oReader)
2 {
3 Boek boek = new Boek();
4 boek.idB= (int)oReader["id"];//id auto generated dus verplicht
5 if(oReader["inventaris_nr"] != DBNull.Value)
6 boek.Inventaris_nrB = (string)oReader["inventaris_nr"];
7 if (oReader["auteurs"] != DBNull.Value)
8 boek.AuteursB = (string)oReader["auteurs"];
9 boek.TitelB = (string)oReader["titel"];//titel verplicht
10 if (oReader["taal"] != DBNull.Value)
11 boek.TaalB = (string)oReader["taal"];
12 if (oReader["uitgeverij"] != DBNull.Value)
13 boek.UitgeverijB = (string)oReader["uitgeverij"];
14 if (oReader["aantal_p"] != DBNull.Value)
15 boek.Aantal_pB = (string)oReader["aantal_p"];
16 if (oReader["jaartal"] != DBNull.Value)
17 boek.JaartalB = (int)oReader["jaartal"];
18 if (oReader["keywords"] != DBNull.Value)
19 boek.KeywordsB = (string)oReader["keywords"];
20 if (oReader["categorie"] != DBNull.Value)
21 boek.CategorieB = (string)oReader["categorie"];
22 if (oReader["standplaats"] != DBNull.Value)
23 boek.StandplaatsB = (string)oReader["standplaats"];
24 if (oReader["ISBN13"] != DBNull.Value)
25 boek.ISBN13 = (string)oReader["ISBN13"];
26 if (oReader["ISBN10"] != DBNull.Value)
27 boek.ISBN10 = (string)oReader["ISBN10"];
28 if (oReader["URL"] != DBNull.Value)
29 boek.UrlB = (string)oReader["URL"];
30 if (oReader["username"] != DBNull.Value)
31 boek.UsernameB = (string)oReader["username"];
32 if (oReader["passwoord"] != DBNull.Value)
33 boek.PasswoordB = (string)oReader["passwoord"];
34 if (oReader["datumB"] != DBNull.Value)
35 boek.DatumBoek = (DateTime)oReader["datumB"];
36 if (oReader["status"] != DBNull.Value)
37 boek.StatusB = (string)oReader["status"];
38
39
40 return boek;
41 }
  

Conversion failed when converting datetime from character string.

That's the error I get by the way. It also appears when I do a search and I don't use the date function... for example when I only fill in the title textbox and I don't select any dates from the calendars...

Sorry for the long post, but I think it's the only way to get a clear view on it...

View 2 Replies


ADVERTISEMENT

Conversion Failed When Converting Character String To Smalldatetime Data Type

Oct 12, 2006

I am newbie in asp and sql, and I am using VS & SQL expresswhen I try to submit I get following error"Conversion failed when converting character string to smalldatetime data type"Following is my insert statement<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:oncallConnectionString %>"SelectCommand="SELECT data.* FROM data" InsertCommand="INSERT INTO data(Apps, Location, Impact, System, Date, Start_Time, End_Time, Duration, Problem, Cause, Solution, Case, Comments) VALUES ('@DropDownList1','@DropDownList2','@DropDownList3','@TextBox6','@DropDownCalendar1','@DropDownCalendar2','@DropDownCalendar3','@TextBox1','@TextBox2','@TextBox3','@TextBox4','@TextBox5','@TextBox7')"></asp:SqlDataSource>These are @DropDownCalendar1','@DropDownCalendar2','@DropDownCalendar3' defined as datetime in database.I would appriciate if somebody could help.

View 7 Replies View Related

Conversion Failed When Converting Character String To Smalldatetime Data Type.

Mar 25, 2007

Hello, I have problem with this code.(This program presents - there is GridView tied to a SQL database that will sort the data selected by a dropdownList at time categories. There are  2  time categories in DropDownList - this day, this week.
 Problem: when I choose one categorie in dropDownlist for examle this week and submit data on the server I got this error.
Conversion failed when converting character string to smalldatetime data type.
Here is code:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
 
 
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
 
string datePatt = @"yyyymmdd";
// Get start and end of day
DateTime StartDate = DateTime.Today;
 
string @StartDate1 = StartDate.ToString(datePatt);
 
string @EndDate = StartDate.AddDays(1).ToString(datePatt);
// Get start and end of week
string @startOfWeek = StartDate.AddDays(0 - (int)StartDate.DayOfWeek).ToString(datePatt);
string @startOfNextWeek = StartDate.AddDays(7 - (int)StartDate.DayOfWeek).ToString(datePatt);
 
 
switch (DropDownList1.SelectedValue)
{
 
case "1":
// day
SqlDataSource1.SelectCommand = "SELECT [RC_USER_ID], [DATE], [TYPE] FROM [T_RC_IN_OUT]" + "WHERE" + "[DATE] >=" + "'@StartDate1'" + " AND [DATE] < " + "'@EndDate'";
break;
case "2":
//week
SqlDataSource1.SelectCommand = "SELECT [RC_USER_ID], [DATE], [TYPE] FROM [T_RC_IN_OUT]" + "WHERE" + "[DATE] >=" + "'@startOfWeek'" + "AND [DATE] <" + "'@startOfNextWeek'";
break;
 
}
 
}
 
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
<style type="text/css">
body {
font: 1em Verdana;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
&nbsp;&nbsp;
 
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
Style="z-index: 100; left: 414px; position: absolute; top: 22px">
<asp:ListItem Selected="True" Value="1">jeden den</asp:ListItem>
<asp:ListItem Value="2">jeden tyden</asp:ListItem>
</asp:DropDownList>
 
<asp:GridView ID="GridView1" runat="server" Style="z-index: 102; left: 228px; position: absolute;
top: 107px" DataSourceID="SqlDataSource1" AutoGenerateColumns="True">
 
</asp:GridView>
&nbsp; &nbsp;<br/> <br/>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=CRSQLEXPRESS;
Initial Catalog=MyConn;Integrated Security=True"
ProviderName="System.Data.SqlClient"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
 

View 4 Replies View Related

Conversion Failed When Converting Character String To Smalldatetime Data Type

Oct 3, 2007

I am running the following query:
 select distinct hqvend, hqvprd,fprod,idesc,ilead,sum(cast(fqty as int) )as fqty, (cast(hqvend as varchar(5))+'/'+ltrim(rtrim(fprod))+'/'+cast(ilead as varchar(3))) as Keydata,'L1/'+rtrim(fprod) as LocPartno from tblkfpl01 inner join hqtl01 on (fprod=hqprod) inner join iiml01 on (hqvend=ivend and hqprod=iprod) where  cast(cast(hqeff as varchar(8)) as smalldatetime) <= (Select CONVERT(varchar(8), getdate(), 1)) and  cast(HQDIS as varchar(8)) >= (Select CONVERT(varchar(8), getdate(), 1))  and hqvend like '134%' group by hqvend,fprod,hqvprd,idesc,ilead   order by hqvend,fprod
The bold sections are giving me the error message. The query works as written above, butis only evaluating on one date, contained in hqeff. However, when I try to modify the second date, HQDIS, by casting it the same way as the one before it:
 select distinct hqvend, hqvprd,fprod,idesc,ilead,sum(cast(fqty as int) )as fqty, (cast(hqvend as varchar(5))+'/'+ltrim(rtrim(fprod))+'/'+cast(ilead as varchar(3))) as Keydata,'L1/'+rtrim(fprod) as LocPartno from tblkfpl01 inner join hqtl01 on (fprod=hqprod) inner join iiml01 on (hqvend=ivend and hqprod=iprod) where  cast(cast(hqeff as varchar(8)) as smalldatetime) <= (Select CONVERT(varchar(8), getdate(), 1)) and  cast(cast(HQDIS as varchar(8)) as smalldatetime) >= (Select CONVERT(varchar(8), getdate(), 1))  and hqvend like '134%' group by hqvend,fprod,hqvprd,idesc,ilead   order by hqvend,fprod
I get the error message. I need to select based on both dates (hqeff AND HQDIS), but cannot seem to be able to it.... Both fields are of type Dedimal, with a length of 8, and dates stored in them look like: 20071003 (YYYYMMDD).
Any suggestions?

View 2 Replies View Related

Conversion Failed When Converting Character String To Smalldatetime Data Type

Oct 21, 2007

Hi,

I have SQL Server 2005 database table with the following data definition as follows:

ID int
LST_TIME varchar(5)
LST_DATE varchar(21)
LST_WEEK int
SUBJECT varchar(100)


Date format (Month,day YEAR) eg.- October, 21 2007
Time format, 00 - 23 hours, HH:MM eg. - 18:58

, and a VB code as below:

Dim Command As New SqlClient.SqlCommand("SELECT * FROM dbo.LISTS WHERE (LST_WK = DATEPART(wk, GETDATE())) AND (CONVERT(datetime, LST_DATE) = CONVERT(datetime, CONVERT(varchar, GETDATE(), 110)))
AND(CONVERT(smalldatetime, LST_TIME) = CONVERT(smalldatetime, CONVERT(varchar(5), GETDATE(), 108)))", conn)

Dim dataReader As SqlClient.SqlDataReader = Command.ExecuteReader(CommandBehavior.CloseConnection)
While dataReader.Read()

Dim NewAlert As New Alert(dataReader("SUBJECT").ToString(), DateTime.Parse(dataReader("LST_DATE").ToString(),
DateTime.Parse(dataReader("LST_TIME").ToString())))

:
:
:
I am encountering error: System.Data.SqlClient.SqlException: Conversion failed when converting character string to smalldatetime data type, which points to the codes in bold. Just wondering anyone out there has got a solution to my problem. Thank you.

View 5 Replies View Related

Conversion Failed When Converting Character String To Smalldatetime Data Type

Apr 10, 2008

Recently i traspased a database from sql server 2000 in spanish to sql server 2005 in english. I change the language of the user sa to spanish and the database is in spanish. . The problem is our dateformat is dmy, i try to force with set dateformat dmy, but always i execute a stored procedure that have a date as input it fail. The error is:

Msg 295, Level 16, State 3, Procedure pa_CalendarioGestion, Line 40
Conversion failed when converting character string to smalldatetime data type.

The code of stored procedure in this line is:

set @diaActual = dateadd("d", @i, @fechaInicio)

This stored procedure in sql server 2000 in spanish not have any problems. For this reason i think the problem is in the configuration.

I hope someone can help me. Thanks.

View 10 Replies View Related

Conversion Failed When Converting Character String To Smalldatetime Data Type

Oct 10, 2006

I am newbie in asp and sql, and I am using VS & SQL express

when I try to submit I get following error

"Conversion failed when converting character string to smalldatetime data type"

Following is my insert statement

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:oncallConnectionString %>"

SelectCommand="SELECT data.* FROM data" InsertCommand="INSERT INTO data(Apps, Location, Impact, System, Date, Start_Time, End_Time, Duration, Problem, Cause, Solution, Case, Comments) VALUES ('@DropDownList1','@DropDownList2','@DropDownList3','@TextBox6','@DropDownCalendar1','@DropDownCalendar2','@DropDownCalendar3','@TextBox1','@TextBox2','@TextBox3','@TextBox4','@TextBox5','@TextBox7')">

</asp:SqlDataSource>

These are @DropDownCalendar1','@DropDownCalendar2','@DropDownCalendar3' defined as datetime in database.

I would appriciate if somebody could help.

Thanks

View 3 Replies View Related

Stored Proc Error: Error Converting Character String To Smalldatetime Data Type

Feb 12, 2005

I am trying to create a page that adds users to a MS SQL database. In doing so, I have run into a couple errors that I can't seem to get past. I am hoping that I could get some assistance with them.

Error from SQL Debug:
---
Server: Msg 295, Level 16, State 3, Procedure AdminAddUser, Line 65
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting character string to smalldatetime data type.
---

Error from page execution:
---
Exception Details: System.Data.OleDb.OleDbException: Error converting data type varchar to numeric.

Source Error:

Line 77: cmd.Parameters.Add( "@zip", OleDbType.VarChar, 100 ).Value = Request.Form("userZip")
Line 78:
Line 79: cmd.ExecuteNonQuery()
---


Below is what I currently have for my stored procedure and the pertinent code from the page itself.

Stored Procedure:
---
CREATE PROCEDURE dbo.AdminAddUser( @username varchar(100),
@password varchar(100),
@email varchar(100),
@acct_type varchar(100),
@realname varchar(100),
@billname varchar(100),
@addr1 varchar(100),
@addr2 varchar(100),
@city varchar(100),
@state varchar(100),
@country varchar(100),
@zip varchar(100),
@memo varchar(100) )
AS
BEGIN TRAN

--
-- Returns 1 if successful
-- 2 if username already exists
-- 0 if there was an error adding the user
--

SET NOCOUNT ON
DECLARE @error int, @rowcount int

--
-- Make sure that there isn't already a user with this username
--

SELECT userID
FROM users
WHERE username=@username

SELECT @error = @@ERROR, @rowcount = @@ROWCOUNT

IF @error <> 0 OR @rowcount > 0 BEGIN
ROLLBACK TRAN
RETURN 2
END

--
-- Set expiration date
--

DECLARE @expDate AS smalldatetime

IF @acct_type = "new_1yr" BEGIN
SET @expDate = DATEADD( yyyy, 1, GETDATE() )
END

IF @acct_type = "new_life" BEGIN
SET @expDate = DATEADD( yyyy, 40, GETDATE() )
END

DECLARE @paidCopies AS decimal
SET @paidCopies = 5


--
-- Add this user to the database
--

IF @acct_type <> "new" BEGIN

INSERT INTO users (userName, userPassword, userEmail, userJoinDate,
userPaidCopies, userExpirationDate, userLastPaidDate,
userBname, userRealName, userAddr1, userAddr2, userCity,
userState, userCountry, userZip, userMemo )
VALUES (@username, @password, @email, GETDATE(), @realname, @billname,
@paidCopies, @expDate, GETDATE(), @addr1, @addr2, @city, @state, @country, @zip, @memo )

SELECT @error = @@ERROR, @rowcount = @@ROWCOUNT

IF @error <> 0 OR @rowcount < 1 BEGIN
ROLLBACK TRAN
RETURN 0
END

END

IF @acct_type = "new" BEGIN

INSERT INTO users (userName, userPassword, userEmail, userJoinDate,
userBname, userRealName, userAddr1, userAddr2, userCity,
userState, userCountry, userZip, userMemo )
VALUES (@username, @password, @email, GETDATE(), @realname, @billname,
@addr1, @addr2, @city, @state, @country, @zip, @memo )

SELECT @error = @@ERROR, @rowcount = @@ROWCOUNT

IF @error <> 0 OR @rowcount < 1 BEGIN
ROLLBACK TRAN
RETURN 0
END

END



COMMIT TRAN
RETURN 1
GO
---


Page Code:
---
Sub AddUser(Sender as Object, e as EventArgs)

Dim db_conn_str As String
Dim db_conn As OleDbConnection
Dim resultAs Int32
Dim cmdAs OleDbCommand


db_conn_str = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=xxxxx; User ID=xxxxx; PWD=xxxxx;"
db_conn = New OleDbConnection( db_conn_str )
db_conn.Open()

cmd = new OleDbCommand( "AdminAddUser", db_conn )
cmd.CommandType = CommandType.StoredProcedure

cmd.Parameters.Add( "result", OleDbType.Integer ).Direction = ParameterDirection.ReturnValue

cmd.Parameters.Add( "@username", OleDbType.VarChar, 100 ).Value = Request.Form("userName")
cmd.Parameters.Add( "@password", OleDbType.VarChar, 100 ).Value = Request.Form("userPass")
cmd.Parameters.Add( "@email", OleDbType.VarChar, 100 ).Value = Request.Form("userEmail")
cmd.Parameters.Add( "@acct_type", OleDbType.VarChar, 100 ).Value = Request.Form("userEmail")
cmd.Parameters.Add( "@realname", OleDbType.VarChar, 100 ).Value = Request.Form("userRealName")
cmd.Parameters.Add( "@billname", OleDbType.VarChar, 100 ).Value = Request.Form("userBname")
cmd.Parameters.Add( "@addr1", OleDbType.VarChar, 100 ).Value = Request.Form("userAddr1")
cmd.Parameters.Add( "@addr2", OleDbType.VarChar, 100 ).Value = Request.Form("userAddr2")
cmd.Parameters.Add( "@city", OleDbType.VarChar, 100 ).Value = Request.Form("userCity")
cmd.Parameters.Add( "@state", OleDbType.VarChar, 100 ).Value = Request.Form("userState")
cmd.Parameters.Add( "@country", OleDbType.VarChar, 100 ).Value = Request.Form("userCountry")
cmd.Parameters.Add( "@memo", OleDbType.VarChar, 100 ).Value = Request.Form("userMemo")
cmd.Parameters.Add( "@zip", OleDbType.VarChar, 100 ).Value = Request.Form("userZip")

cmd.ExecuteNonQuery()

(...)

---

View 1 Replies View Related

Syntax Error Converting Character String To Smalldatetime Data Type.

Aug 8, 2005

Hi guys and gals,I have the following code:CREATE PROCEDURE searchRecords(     @searchFor  NVarchar (25)  = NULL,     @fromDate  NVarchar (25)  = NULL,     @toDate  NVarchar (25)  = NULL)
AS
IF @fromDate IS NOT NULL     DECLARE @fromDateString VarChar(200)     SET @fromDateString = '  CONVERT(smalldatetime, ''' + @fromDate + ''') '
IF @toDate IS NOT NULL     DECLARE @toDateString VarChar(200)     SET @toDateString = '  CONVERT(smalldatetime, ''' + @toDate + ''') '
SELECT * FROM MIPR WHERE      ID = @searchFor      OR DESC_QTY = @searchFor      OR REQ_ACTIVITY = @searchFor      OR ACC_ACTIVITY = @searchFor      OR MANYEARS = @searchFor      OR TECH_POC = @searchFor      OR RESOURCE_POC = @searchFor      OR SI_DATE BETWEEN @fromDateString   AND  @toDateString;GOit creates an error that I can't seem to fix. the error I get is:Syntax error converting character string to smalldatetime data type.How can I fix this? Thanks in advance!

View 1 Replies View Related

The Conversion Of Char Data Type To Smalldatetime Data Type Resulted In An Out-of-range Smalldatetime Value

Mar 30, 2007

I am using Visual Studio 2005 and SQL Express 2005. The database was converted from MS Access 2003 to SQL Express by using the upsize wizard.



I would like to store the current date & time in a column in a table. This column is a smalldatetime column called 'lastlogin'.

The code I'm using is:



Dim sqlcommand As New SqlCommand _

("UPDATE tableXYZ SET Loggedin = 'True', LastLogin = GetDate() WHERE employeeID = '" & intEmployeeID.ToString & "'", conn)



Try

conn.Open()

sqlcommand.ExecuteNonQuery()

conn.Close()

Catch ex As Exception

MessageBox.Show(ex.Message)

End Try



This code works fine on my local machine and local SQL server. However at the client side this code results in the error as mentioned in the subject of this thread. I first used 'datetime.now' instead of 'getdate()', but that caused the same error. Then I changed the code to 'getdate()', but the error still remains.



The server at the client is running Windows Server 2000 UK . My local machiine is running WIndows XP Dutch.

Maybe the conversion from Dutch to UK has something to do with it. But this should be solved by using the 'Getdate()' function..... ?













View 1 Replies View Related

Datetime And Conversion To Smalldatetime.

Jan 15, 2006

I am placing DateTime into SQL using an ASP.NET form. The date should be formatted dd/mm/yyyy hh/mm/ss.

I am getting the error below. Is there any way to convert the format of the DateTime function from the ASP.NET end?

Thanks

mes


"The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value"

View 1 Replies View Related

Conversion Of Nvarchar To Smalldatetime

Jul 31, 2007

Hi,
when I convert a field into smalldatetime from nvarchar(50) in Sql Server 2000, i got a default value (1900-01-01 00:00:00) for that field.Actually value of that field to be changed as different values).I want to be convert bulk of records.please help me.

current data

pvdate(nvarchar(50))
------
12/03/2007

Data to be changed into

pvdate(smalldatetime)
--------------------
2007-03-12 12:00:00

View 10 Replies View Related

Date Conversion From Char To Smalldatetime

Dec 3, 2000

Hi All,
I am trying to convert date from a character string field 12 to another database which has smalldatetime. Is there a way to do this. Any help would be greatly appriciated.

cheers
dave

View 4 Replies View Related

Why Am I Getting An Error Runtime Error Conversion String Type Pr_h_reqby To Int

Jan 17, 2007

here is my code the falue of pr_h_reqby is "Test" 
Dim strconn As New SqlConnection(connstring)
Dim myReqdata As New DataSet
Dim mycommand As SqlDataAdapter
Dim sqlstr As String = "select pr_H_reqby from tbl_pr_header where pr_h_recid = " & recid & ""
mycommand = New SqlDataAdapter(sqlstr, strconn)
mycommand.Fill(myReqdata, "mydata")
If myReqdata.Tables(0).Rows.Count > 0 Then
'lblReqID.Text = myReqdata.Tables(0).Rows("reqid").ToString
lblNameVal.Text = myReqdata.Tables("mydata").Rows("pr_H_reqby").ToString()
lblEmailVal.Text = myReqdata.Tables("mydata").Rows("pr_h_reqemail").ToString()
lblReqDateVal.Text = myReqdata.Tables("mydata").Rows("pr_h_reqdate").ToString()
lblneedval.Text = myReqdata.Tables("mydata").Rows("pr_h_needdt").ToString()
lblDeptval.Text = myReqdata.Tables("mydata").Rows("pr_h_dept").ToString()
txtbxReqDesc.Text = myReqdata.Tables("mydata").Rows("pr_h_projdesc").ToString()
End If

View 1 Replies View Related

Conversion Error With SQL Command String

May 26, 2008

Hi,

When I use the folowing code, the first (green) line is executed well.
The composed SQL statement (red) gives a conversion error.


declare @vchSQL_Cmd varchar(max),

@intMaxNr int,

@vchTabelNaam varchar(255),

@vchKolomNaam varchar(255)



set @vchTabelNaam = 'CI_Lei_Toestand_DetailLijnen'

set @vchKolomNaam = 'CameraInspectieID'



select @intMaxNr = max(CI_Lei_Toestand_DetailLijnen.CameraInspectieID) from CI_Lei_Toestand_DetailLijnen

select @intMaxNr


set @vchSQL_Cmd =

'select @intMaxNr = max(' + @vchTabelNaam + '.' + @vchKolomNaam + ') from ' + @vchTabelNaam

select @vchSQL_Cmd

exec (@vchSQL_Cmd)

select @intMaxNr


Thx

View 3 Replies View Related

Conversion From String To Type Date Error

Mar 20, 2008

 I have a web page which executes a stored procedure with several parameters. On execution I get an error for the following piece of code. I will be passing null value to the stroed procedure for this parameter "ActiveDate". 
Dim parameterActivedate As SqlParameter = objCommand.Parameters.Add("@Activedate", SqlDbType.DateTime)
parameterActivedate.Value = ""
The error is:
System.InvalidCastException: Conversion from string "" to type 'Date' is not valid. at Microsoft.VisualBasic.CompilerServices.Conversions.ToDate(String Value) at webpage.Do_Update(Object Sender, EventArgs e) 

View 3 Replies View Related

String/Date Concatenation Causes Conversion Error - Streamline Fix Suggestions

Sep 4, 2007

Hi,I'm trying to concatenate a Description (nchar(100)) and Date(datetime) as Description and my initial effort was just"...description+' '+open_date as description..." which throws a date/string conversion error; finally came up with a working string belowbut don't think it's the optimal way to do this - any suggestions?select (rtrim(description)+''+rtrim(convert(char(2),datepart(mm,open_date)))+'/'+convert(char(2),datepart(dd,open_date))+'/'+convert(char(4),datepart(yyyy,open_date))) as description fromoncd_opportunity where opportunity_id=?open_date is not a required field at the db level, but it is requiredon the form so it should not be null as a rule.

View 2 Replies View Related

How Can I Find Values Outside Of The Smalldatetime Range?

Mar 25, 2008

I have a field which is currently of the "date time" data type. i want to convert it to smalldatetime, but everytime I try, i get an error of the "The conversion from datetime data type to smalldatetime data type resulted in a smalldatetime overflow error. " sort.

I have tried to find the values which are out of the smalldatetime range, with the following query


SELECT *

FROM midmar

WHERE bday BETWEEN '01/01/1900' AND '06/05/2079'




Which doesn't quite work, and gives me values that are actually between those two values listed.

I have also tried having the WHERE clause read:

WHERE bday <'06/06/2079' AND

bday>'01/01/1900'


and that doesn't really work either.

What's going on? Is there likely another problem besides the structuring of my queries?

View 9 Replies View Related

Sql Insert Conversion Failed When Converting From A Character String To Uniqueidentifier. Error With Parameters

Dec 28, 2007

Hi,I'm new at asp .net and am having a problem. On a linkbutton click event, I want to insert into my db a row of data which includes two parameters. Param1 is the id of the logged in user, and Param2 is  <%#DataBinder.Eval(Container.DataItem, 'UserId')%> which is the username of a user given through a datalist.When I execute the query:   "insert into aspnet_friendship (userId, buddyId) values (@Param1, @Param2)"I get the error: Conversion failed when converting from a character string to uniqueidentifier.I am trying to insert these into my table aspnet_friendship into the columns userId and buddyId which are both uniqueidentifier fields. I tested the query using the same values  (@Param1, @Param1) and (@Param2, @Param2) and found out that the problem is with Param2 because when I use Param1 the insert works perfectly. The value passed by Param2 is supposed to be the id of a user which I get from the datalist which selects * from aspnet_Users, so that <%#DataBinder.Eval(Container.DataItem, 'UserId')%> should also be an Id like Param1 is. Since both params are in the form of .toString(), I don't understand why one works but the other doesn't.As you can see in the code below, both of these parameters are dimmed as strings, so I don't understand why Param2 doesn't work. Can anyone please help?  Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs)                Dim MyConnection As SqlConnection        MyConnection = New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|ASPNETDB.MDF;Integrated Security=True;User Instance=True")        Dim MyCommand2 As SqlCommand                Dim CurrentUser As String        CurrentUser = Membership.GetUser.ProviderUserKey.ToString()        Dim add As String        add = "<%#DataBinder.Eval(Container.DataItem, 'UserId')%>".ToString()        Session("username") = User.Identity.Name                Dim InsertCmd As String = "insert into aspnet_friendship (userId, buddyId) values (@Param1, @Param2)"                MyCommand2 = New SqlCommand(InsertCmd, MyConnection)                MyCommand2.Parameters.AddWithValue("@Param1", CurrentUser)        MyCommand2.Parameters.AddWithValue("@Param2", add)               MyCommand2.Connection.Open()        MyCommand2.ExecuteNonQuery()        MyCommand2.Connection.Close()    End Sub Thank you. 

View 3 Replies View Related

Error At Login Page: Conversion Failed When Converting From A Character String To Uniqueidentifier.

Jan 5, 2008

Hello,  Im Getting an error (below) at the login page. The only control on
that page is a Login control, adn the error below comes when I click login. Does anyone know what Im doing wrong? This is my login page:<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" Title="myapp- Login" %><asp:Content ID="Content1" ContentPlaceHolderID="ContentHeader" Runat="Server">    LOGIN</asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="ContentBody" Runat="Server">    <table border="1" cellpadding="0" cellspacing="0" width="305">        <tr>            <td class="bodyText" colspan="2" style="height: 20px; text-align: center;">                <p>                    <!-- TemplateBeginEditable name="mainText" -->                    &nbsp;<asp:Login ID="Login1" runat="server" TitleText="Existing Users Log In">                    </asp:Login>                </p>            </td>        </tr>        <tr>            <td style="text-align: right">                <asp:LinkButton ID="lbNewmembers" runat="server" OnClick="lbNewmembers_Click">New Member?</asp:LinkButton></td>            <td>                <asp:LinkButton ID="lbForgotPassword" runat="server" OnClick="lbForgotPassword_Click">Forgot Password?</asp:LinkButton></td>        </tr>    </table></asp:Content>Error: 
Server Error in '/myApp' Application.


Conversion failed when converting from a character string to
uniqueidentifier. 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: Conversion failed when converting from a
character string to uniqueidentifier.Source Error:



An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of the
exception can be identified using the exception stack trace below.
Stack Trace:



[SqlException (0x80131904): Conversion failed when converting from a character string to uniqueidentifier.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +859322 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +736198 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1959 System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +31 System.Data.SqlClient.SqlDataReader.get_MetaData() +62 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +297 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +903 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32 System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +122 System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) +62 System.Web.Security.SqlMembershipProvider.GetPasswordWithFormat(String username, Boolean updateLastLoginActivityDate, Int32& status, String& password, Int32& passwordFormat, String& passwordSalt, Int32& failedPasswordAttemptCount, Int32& failedPasswordAnswerAttemptCount, Boolean& isApproved, DateTime& lastLoginDate, DateTime& lastActivityDate) +1121 System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved, String& salt, Int32& passwordFormat) +105 System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved) +42 System.Web.Security.SqlMembershipProvider.ValidateUser(String username, String password) +83 System.Web.UI.WebControls.Login.OnAuthenticate(AuthenticateEventArgs e) +160 System.Web.UI.WebControls.Login.AttemptLogin() +105 System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +99 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35 System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) +115 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +163 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.312;
ASP.NET Version:2.0.50727.833

View 1 Replies View Related

Transact SQL :: Error - Conversion Failed When Converting Date And / Or Time From Character String

Nov 16, 2015

I've imported a CSV file into a table in SQL Server 2012. It's a large file, 140,000+ rows, so I couldn't covert it to Excel first to preserve the date format due to Excel's row limit. In the CSV file, there were 3 column with date data in "31-Aug-09" format, and the import automatically transformed these in "31AUG09" format (varchar(50)) in SQL Server.  Now I need to convert these 3 columns from varchar to datetime so I could work with them in date format.

I've tried several things,e.g,

select
convert(datetime,
right(admdate,4)+left(admdate,2)+substring(admdate,3,3))

or

select
convert(datetime,
substring(admdate,6,4)+substring(admdate,1,2)+substring(admdate,3,3))

but keep getting the same error message (Msg 241) "Conversion failed when converting date and/or time from character string".

View 4 Replies View Related

Convert String To Smalldatetime

May 4, 2007

Hi,



I am new to SSIS and have been trying to load a date from a Table1.ColumnA (varchar(50)) to a Table2.ColumnB(smalldatetime).



I tried using the Derived Column and Data Conversion controls but I get the below error.

Error converting data type DBTYPE_DBTIMESTAMP to datetime



What do I do to load this data.



Thanks,

Noel

View 8 Replies View Related

SQL Server 2014 :: Find String With Spaces And Replace Them With Other String

Sep 8, 2015

I have following query which return me SP/Views and Functions script using:

select DEFINITION FROM .SYS.SQL_MODULESNow, the result looks like
Create proc
create procedure
create proc
create view
create function

I need its result as:

Alter Procedure
Alter Procedure
Alter Procedure
Alter View
Alter Function

I used following

select replace(replace(replace(DEFINITION,'CREATE PROCEDURE','Alter Procedure'), 'create proc','Alter Procedure'),'create view','Alter View') FROM .SYS.SQL_MODULESto but it is checking fixed space like create<space>proc, how can i check if there are two or more spaces in between create view or create proc or create function, it should replace as i want?

View 5 Replies View Related

Smalldatetime Error 296

Nov 29, 2000

Hi, i´m have a problem with the Convert function in sql 7 enterprise
when i have the value '07-31-1967' format mm-dd-yyyy i recivied the error 296
The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value

the sentence i use is
set @dfnacimien = (Convert(varchar(10),@dfnacimien,110))

Someone please help me!!!!

View 1 Replies View Related

Find In String And Return Part Of String

Mar 21, 2007

I am trying to find a way to find a certian character in a string and then select everything after that character.

for example i would look for the position of the underscore and then need to return everthing after it so in this case

yes_no

i would return no

View 7 Replies View Related

Error : Nvarchar Into Smalldatetime

Jan 21, 2008

Hi !

I am having a problem with MS SQL 2005
for a column
[DateInsert] [smalldatetime] NOT NULL

and that Query

INSERT INTO Users (DateInsert) VALUES (CONVERT(DATETIME,'2007-12-17',120))

I am getting a conversion error : nvarchar into smalldatetime

it seems that I am getting this error only with days > 12

2007-12-17 does not work but 2007-12-01 works


any idea ?
thank you

View 9 Replies View Related

String To Int Conversion

Aug 17, 2004

hi all,
I have writen a function in which I'm selecting max of varchar datatype column after converting it into integer datatype ,though the where condition of the select statement retrives only numbers which are in string format but I'm getting conversion error for a string value which doesn't satisfy the condition. can any one explain this behaviour?
Thanks in advance.

View 6 Replies View Related

Conversion Of String To Int

Jun 25, 2015

I converted a string value to int

CAST(TestSth3.Emp_Code AS int)
it returns 1,234 but i need 1234

i am using vb.net 2008.

View 2 Replies View Related

String To Money Conversion

Jan 25, 2005

have a SQL server table with a vairbale unitCost of type money and via a stored procedure I am trying to update it. Through asp I capture the value as a string and then ATTEMPT to convert it into a variable of type money before executing the stored procedure as follows.

SqlParameter parameterUnitCost= new SqlParameter("@unitCost", SqlDbType.Money,8);
parameterUnitCost.Value = unitCost;
myCommand.Parameters.Add(parameterUnitCost);




This gives me an input string error. On the other hand if I change that line to the following, the page works flawlessley:

SqlParameter parameterUnitCost= new SqlParameter("@unitCost", SqlDbType.Money,8);
parameterUnitCost.Value = 25.45;
myCommand.Parameters.Add(parameterUnitCost);




any thoughts???

View 3 Replies View Related

String To Datetime Conversion

May 30, 2008

Hi,
Ive imported a data set into SQL. Now on redefining a text field to datetime, most dates that are filled come through okay.

The issue is that there are some empty fields which I'd like for it to stay empty after conversion. Now what happens is that the empty field becomes '01/01/1900' - which is throwing off our queries as we need it to be compared to other date fields.

Is there a way to keep it empty even after the datatype is changed to datetime?
Thanks a bunch!

View 5 Replies View Related

String Conversion Question

Nov 7, 2006

Hi guys,

How will I convert this into a string type with Zero Padding on the left?

Say I have an amount of 12345.89, then the result I like is this:
000000001234589

Please help me.

Thank you.

View 7 Replies View Related

Conversion Datetime To String

Jul 20, 2006

Hi
Can we convert DateTime to String. If so how?
Thanks in advance.

Mahathi.

View 1 Replies View Related

Problem With Conversion Of String

Jul 20, 2005

I have a feeling I'm missing something obvious here, but being new toSQL Server is my only excuse!I have a table that holds a variety of data. I am writing a userreport where the user wants to be able to return all data that fallsbetween a start and end date that they enter.The query should therefore be along the lines ofSELECT [some columns]FROM [my_table]WHERE [column holding date] BETWEEN [start date] AND [end date];However, the column holding the date information has been defined, forreasons best known to the designer, as a VARCHAR(10) and the data isin the format dd/mm/yy.I have tried CAST, which simply gave an error. I then tried CONVERTin the form CONVERT(datetime, [column holding date], 3) and the queryruns without error but returns no data, even though I can see there isdata that would meet the criteria in the table.Can anyone help me with a solution to this?ThanksH

View 4 Replies View Related







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