ERROR:Syntax Error Converting Datetime From Character String. With Stored Procedure

Jul 12, 2007

Hi All,





i have migrated a DTS package wherein it consists of SQL task.

this has been migrated succesfully. but when i execute the package, i am getting the error with Excute SQL task which consists of Store Procedure excution.



But the SP can executed in the client server. can any body help in this regard.





Thanks in advance,

Anand

View 4 Replies


ADVERTISEMENT

Error 241: Syntax Error Converting Datetime From Character String

Jan 7, 2004

Hi All, can someone help me,
i've created a stored procedure to make a report by calling it from a website.
I get the message error "241: Syntax error converting datetime from character string" all the time, i tryed some converting things but nothig works, probably it is me that isn't working but i hope someone can help me.
The code i use is:


CREATE proc CP_Cashbox @mID varchar,@startdate datetime,@enddate datetime
as
set dateformat dmy
go
declare @startdate as varchar
declare @enddate as varchar

--print "query aan het uitvoeren"

select sum(moneyout) / sum(moneyin)*100 as cashbox
from dbo.total
where machineID = '@mID' and njdate between '@startdate' and '@enddate'
GO



Thanx in front
Cya

View 14 Replies View Related

Syntax Error Converting Datetime From Character String

Aug 6, 2004

Here's the deal. I'm a newbie trying to update a date (@Effective) in sql server. I've been trying all sorts of things, but nothing seems to work. Here's my current code:

Sub btnUpdate_Click(sender As Object, e As EventArgs)
Dim sqlStmt As String
Dim conString As String
Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim sqldatenull As SqlDateTime
Try
sqlStmt = "UPDATE [Submission] SET [Effective]=Convert(DateTime, '@Effective', 101), "& _
"[Status]=@Status WHERE ([Submission].[Submission]=@Submission)"
conString = "server='(local)'; user id='sa'; password='password'; database='database'"
cn = New SqlConnection(conString)
cmd = New SqlCommand(sqlStmt, cn)

cmd.Parameters.Add(New SqlParameter("@Submission", SqlDbType.Int, 4))
cmd.Parameters.Add(New SqlParameter("@Effective", SqlDbType.VarChar, 10))
cmd.Parameters.Add(New SqlParameter("@Status", SqlDbType.VarChar, 8))

sqldatenull = SqlDateTime.Null

If (txtEffective.Text = "") Then
cmd.Parameters("@Effective").Value = sqldatenull
Else
cmd.Parameters("@Effective").Value = txtEffective.Text
End If
cmd.Parameters("@Status").Value = dropStatus.SelectedItem.Text
cmd.Parameters("@Submission").Value = LabelSubmission.Text

cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Response.Redirect("main.aspx")

Catch ex As Exception
lblError.Text = ex.Message
Finally
cn.Close()
End Try
End Sub


My db is setup as follows:

Submissionint4
Insuredvarchar30
Statevarchar2
Effective datetime 8
Underwritervarchar9
Statusvarchar8
Cleareddatetime 9


I'm losing my hair by the fist full... Somebody please stop the insanity!

View 2 Replies View Related

Syntax Error Converting Datetime From Character String - HELP PLEASE!

Apr 20, 2005

Somewhere, either in the
aspx.vb code, or the stored procedure that's being called, it doesn't
like my code since I am getting the dreaded "syntax error converting
datetime from character string" error.  I've been battling this
for two days - can someone spot what is wrong here?

The dtWdate variable is coming from a calendar control on my aspx page.
Please help - I've tried every conceivable way I can think to do this without success.
Lynnette

Here's the code:
    Private Sub GetFLSAEmpInfoRecs()
        'uses the AppSettings table to generate WHERE clause from the filter values

        Dim dtWdate As DateTime = Calendar1.SelectedDate
        Dim wValue As String = Session("svFilterValue")

        Dim cnn As New SqlConnection(constants.SQLConStrFLSA)
        Dim cmd As New SqlCommand("usp_AddFLSA", cnn)
        cmd.CommandType = CommandType.StoredProcedure
        cnn.Open()

        cmd.Parameters.Add(New
SqlParameter("@dtWDate", SqlDbType.DateTime)).Value =
Convert.ToDateTime(dtWdate)
        cmd.Parameters.Add(New
SqlParameter("@whereString", SqlDbType.VarChar, 500)).Value = wValue
      
        cmd.ExecuteNonQuery()
        cnn.Close()

    End Sub

And here is the stored procedure:

ALTER PROC usp_AddFLSA
  @dtWdate datetime,
  @whereString as varchar(255)
AS
DECLARE @strSQL as varchar(2000)

SET @strSQL =
'
INSERT INTO FLSAEmpInfo
( Emp_Number,
  PT_ID,
  Emp_Division,
  Emp_DeptInfo,
  Emp_Supervisor,
  Emp_Location,
  Emp_Union,
  Emp_SG,
  Emp_Shift,
  WrkDate
)
SELECT
  hcsoSharedTables.dbo.Employee2.Emp_Number,
  hcsoSharedTables.dbo.Employee2.[ID],
  hcsoSharedTables.dbo.Employee2.Division,
 
dbo.udf_getDeptInfo(hcsoSharedTables.dbo.employee2.Department,hcsosharedtables.dbo.employee2.Dept_Mgr,hcsosharedtables.dbo.employee2.job_dept_code),
  hcsoSharedTables.dbo.Employee2.Job_Supervisor,
  hcsoSharedTables.dbo.Employee2.Loc_Name,
  hcsoSharedTables.dbo.Employee2.[Union],
  hcsoSharedTables.dbo.Employee2.Sched_Group,
  hcsoSharedTables.dbo.Employee2.Shift,' +
  @dtWdate + ' ' + 'FROM hcsoSharedTables.dbo.Employee2' + @whereString

EXEC(@strSQL)

View 4 Replies View Related

Syntax Error Converting Datetime From Character String

Nov 14, 2005

Hi all,       The last week this was working, and today i was testing and all start with errors. This is my SQL sentence:command = New SqlCommand("update ctlg_users set u_last_access = '" & FormatDateTime(Now(), 1) & "' where u_id = " & cstr(l_u_id),oConn)Is there an error? why was before working and now don`t?, including an old ASP page that i´m still using fall back to the same error when is using FormatDateTime, í´ve tried in the ASPX page using datetime.now.tostring("dd/mm/yyyy") but i got an error too!! HEEEELP!Thanks :D

View 2 Replies View Related

Msg 241: Syntax Error Converting Datetime From Character String

Nov 24, 2005

Hi,

I'm having a strange problem with the following stored proc:


Code:

sql

declare @orderBy tinyint

set @orderBy = 2

SELECT tblUsers.userID, firstName, lastName, dateRegistered, count(movieSessionID) As sessionsCount FROM tblUsers
LEFT JOIN tblMovieSessions on tblUsers.userID = tblmovieSessions.userID
Group By tblUsers.userID, firstName, lastName, dateRegistered
Order By Case
WHEN @orderBy = 2 THEN firstName
WHEN @orderBy = 3 THEN dateRegistered
WHEN @orderBy = 4 THEN count(movieSessionID)
else lastName
End desc



When I execute it with @orderBy = 1 or 2 I get the following error message: Quote: Server: Msg 241, Level 16, State 1, Line 5
Syntax error converting datetime from character string.

However, with @orderBy = 3 or 4 it executes successfully.

I don't understand why this change should have this impact because the error seems to be occuring on the first line (i.e. SELECT...).

If I take the dateRegistered column out of the query I get a new error message:

Quote:
Server: Msg 245, Level 16, State 1, Line 5
Syntax error converting the nvarchar value 'Adam' to a column of data type int.

I don't understand why it is trying to convert these columns during the query anyway, let alone how to solve the problem.

Anyone got any ideas?

View 1 Replies View Related

Syntax Error Converting Datetime From Character String

Sep 29, 2005

I am using INSERT to replace about 160 fields for one company in the company table, all goes well until I come to the Rn_edit_date field which is a datetime datatype. When I insert the value of:

cast('2005-03-15 09:25:44.463' as datetime)

Error message as a result is: Syntax error converting datetime from character string.

NOTE: 2005-03-15 09:25:44.463 is the correct format which all other companies abide by, so I'm totally lost at where I'm going wrong?

Any help would be appreciated

View 5 Replies View Related

SQL Syntax Error Converting Datetime From Character String

Jun 22, 2007

I am having a problem on running the following queiry




select * from my_table where unitclass_id=247
and Year(cast (column1 as datetime))=Year(dateadd(wk,0,getdate()) )





column1 type nvarchar(10) and stores date in format like 2007-06-22.



I am trying to select all records for the current year from my_table and getting an error

when running that queiry



Syntax error converting datetime from character string.



Please help



Thank you



View 8 Replies View Related

Syntax Error Converting Datetime From Character String.

Mar 6, 2008

I have a field that has dates that are currently set as a string. Dates are as follows:

Apr 01 2006
Aug 20 2006
Aug 20 2006

I did an isdate() function on the field to see if it can be converted and it came back as true; however, I have attempted several different ways to convert the field to a date field and it continues to give me a syntax error. Any assistance would be great!!!

I tried:
convert(datetime,cast(New_Date as varchar),100)
convert(varchar(25),New_Date,107)
Both gave me syntax errors.

View 10 Replies View Related

Syntax Error Converting Datetime From Character String.

Nov 14, 2007



When I convert this data into a datetime, i get the foll error.
Syntax error converting datetime from character string.


SELECT convert(datetime,'09/2007')

Basically I have a field in a tbl that has varchar datatype, and is in this format of mm-yyyy. I need to compare this value to current date and so I convert it to datetime. but it errs
Pl help

View 3 Replies View Related

'Syntax Error Converting Datetime From Character String' With Sp_executesql

Jul 20, 2005

CREATE PROCEDURE dbo.Synchronization_GetNewRecords(@item varchar(50),@last datetime)ASSET NOCOUNT ONDECLARE @sql nvarchar(4000)SET @sql = 'SELECT * FROM ' + @item + ' WHERE LastUpdated >' + @lastEXEC sp_executesql @sql, N'@Type varchar(50), @Last datetime', @item, @lastThis is my SP. Very simple. But it is throwing the error in the subject line.Any help would be greatly appreciated.

View 1 Replies View Related

Syntax Error Converting Datetime From Character String (2000)

May 22, 2008

i have a stored proc running against the Northwind DB




Code Snippet
CREATE PROCEDURE CustomPaging
@intOrderID varchar(10),
@strCustomerID varchar(10),
@intEmployeeID int,
@dteOrderDate datetime,

@startRowIndex int,
@maximumRows int,
@SortOrder int
AS


DECLARE @TempItems TABLE
(
ID int IDENTITY,
OrderID int
)
DECLARE @maxRow int
SET @maxRow = (@startRowIndex + @maximumRows) - 1
SET ROWCOUNT @maxRow
INSERT INTO @TempItems (OrderID)
SELECT OrderID
FROM Orders o
INNER JOIN Customers c ON c.CustomerID = o.CustomerID
INNER JOIN Employees e ON e.EmployeeID = o.EmployeeID
ORDER BY CASE @SortOrder WHEN 0 THEN OrderID
WHEN 1 THEN c.CompanyName
WHEN 2 THEN e.FirstName
WHEN 3 THEN o.OrderDate
WHEN 4 THEN o.RequiredDate
WHEN 5 THEN o.ShippedDate END

SET ROWCOUNT @maximumRows
SELECT o.OrderID, CompanyName, e.FirstName + ' ' + e.LastName EmployeeName, o.OrderDate, o.RequiredDate, o.ShippedDate
FROM @TempItems t
INNER JOIN Orders o ON o.OrderID = t.OrderID
INNER JOIN Customers c ON c.CustomerID = o.CustomerID
INNER JOIN Employees e ON e.EmployeeID = o.EmployeeID
WHERE
t.[ID] >= @startRowIndex
AND
(o.OrderID LIKE @intOrderID OR @intOrderID = '')
AND
(o.CustomerID = @strCustomerID OR @strCustomerID='')
AND
(o.EmployeeID = @intEmployeeID OR @intEmployeeID = 0)
AND
(o.OrderDate = @dteOrderDate OR @dteOrderDate IS NULL)
SET ROWCOUNT 0
GO






when i execute the sp with @sortOrder = 0, it works fine
exec CustomPaging '','',0,null, 1, 10, 0

but if i try anything else (@SortOrder=1) i get the error message
exec CustomPaging '','',0,null, 1, 10, 1
Syntax error converting datetime from character string.

but im unsure what is causing this problem? and how to sort it?

Any help is greatly appreciated.

Cheers.
Craig

View 13 Replies View Related

Syntax Error Converting Datetime From Character St

Jun 4, 2007

Probably one of the easiest queries some have seen around, but good ol' MS and their dates. I can't get around this error on this simple query. It will be a job that will run probably several times a day. I haven't even gotten passed to the second part of it....I've also seen this error is a VERY popular error, even with advanced programmers it seems. WOW. Basically, I want to keep the row count to 2 days. Well, if you have any suggestions, I'd take 'em. Thanks!

Delete from tblCallIndexes where inum in
(select inum from tblCalls where StartedAt < 'DATEADD(d,-2,GETDATE())')

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

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

Converting A String To Datetime In A Stored Procedure

Aug 19, 2004

I have a stored procedure called from ASP code, and when it is executed, the stored procedure takes in a date as an attribute.

But since the stored procedure call is really just a string in the code, it is taking in the value as a string. So in my stored procedure, I want to convert a string value to a date value.

Any idea how this is done?

View 1 Replies View Related

Converting Datetime From Character String

Jun 28, 2004

Hi there,

I have the following code:

Dim CityTown As String = Ctype(Request.Querystring("CityTown"), String)
Dim Suburb As String = Ctype(Request.Querystring("Suburb"), String)
Dim SuburbValue As String = Ctype(Request.Querystring("Suburb"), String)
Dim Rooms As String = Ctype(Request.Querystring("Rooms"), String)
Dim Rent As String = Ctype(Request.Querystring("Rent"), String)

Dim DateToday = DateTime.Now
Dim mySQL AS String
If suburbValue = "- All -" Then
mySQL = "SELECT propListID, propListExpires, propBuildType, propRoomNumber, propRentPerWeek, propDescription, propCityTown, propSuburb FROM tblPropertyList WHERE [propCityTown]='" & CityTown & "' AND [propRentPerWeek]<= '" & Rent & "' AND [propRoomNumber]='" & Rooms & "'AND [propListExpires] >='" & DateToday & "' "


However I am having trouble getting the Date to work as part of my SQL String. I keep getting the following error:

Syntax error converting datetime from character string.
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: Syntax error converting datetime from character string.

Source Error:


Line 30: MyDA = New SqlDataAdapter (mySQL, myConn)
Line 31: myDS = New DataSet()
Line 32: myDA.Fill(MyDS)
Line 33:
Line 34: dlPropertyListing.Datasource = MyDS.Tables(0)


Source File: K:detailsdetailspropertylisting.aspx Line: 32


Any ideas how to resolve this?? I do not want to use Parameters in my statement.

Thanks in advance,

TCM

View 3 Replies View Related

Converting Datetime From Character String

Dec 2, 2004

Can anyone tell me what this error message means and how I can correct it on my statement:
Code:

Server: Msg 241, Level 16, State 1, Line 1Syntax error converting datetime from character string.

Here's my query statement:
Code:

SELECT animalid AS "Animal ID", name AS "Name", categoryid AS "Category ID", DATENAME(MONTH, dateBorn) + ' ' + DATENAME(DAY, dateBorn) + ', ' + DATENAME(YEAR, dateBorn) AS "Date of Birth"FROM animalWHERE categoryid = 'Cat' AND dateBorn = 'May%'

I know it has something to do with: dateBorn = 'May%' because when I took out Quote: AND dateBorn = 'May%' I get results, but I need to narrow it down to list the cats born in May.

View 6 Replies View Related

Converting Datetime From Character String

Aug 14, 2007

I am trying to select all members from a SQL db who have a renewal date btw to dates inputted into two text fields, but I am now getting the error above. This is where the problem is coming in...

If strStartDate <> "" and strEndDate <> "" Then
If bParam = True Then
StrSQL = strSQL & " AND "
Else
StrSQL = strSQL & " WHERE deleted=0 AND "
End If
strSQL = strSQL & "renewal_due BETWEEN '%" & Replace(strStartDate,"'","''") & "%' AND '%" & Replace(strEndDate,"'","''") & "%' "
End If


Any help would be greatly appreciated!

Thank you...

View 7 Replies View Related

Error Converting Datetime To String.

Jun 6, 2008

I have a dropdown list thats boudn to a SqlDataSource.  The DataSource looks like this:
  <asp:SqlDataSource ID="dsProgramList" runat="server" ConnectionString="<%$ ConnectionStrings:csData %>"
SelectCommand="SELECT DISTINCT [Program_Name] +','+ [Begin_Date] AS NAMEandDATE, [Course_ID], [LOC] FROM [ThisTable] WHERE ([LOC] = @LOC)">
<SelectParameters> 
 
Where the dropdownlists text = NAMEandDATE and its value = Course_ID
When I select the LOC from the LOCdropdownlist, the dropdownlist in question updates, and an error "Erro converting datetime from character string" happens?
Any suggestions?

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

T-SQL (SS2K8) :: Error Converting Datetime To String

May 29, 2014

I am trying to create a stored procedure that Pulls in Chargeable and Non Chargeable hours for our employees however When I run the Stored Procedure I get this error "Conversion failed when converting date and/or time from character string." I am having a hard time figuring out were this is happening in the Stored Procedure. Also I would like to be able to Add a parameter that would be the StartDate and EndDate for which the stored procedure would pull time for.

ALTER PROCEDURE [dbo].[Chargeability]
-- Add the parameters for the stored procedure here
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

[Code] ......

View 9 Replies View Related

Conversion Failed When Converting Datetime From Character String.

Jan 17, 2008

Hi,
I am getting the following error when
executing the ExecuteInsert in the code below..:
 
Conversion failed when converting
datetime from character string.



    private bool
ExecuteInsert(String quantity)   
{[snip]       
con.Open();       
SqlCommand command = new SqlCommand();       
command.Connection = con;       
TextBox TextBox1 =
(TextBox)FormView1.FindControl("TextBox1");       
Label 1 = (Label)FormView1.FindControl("Label3");       
Label 2 = (Label)FormView1.FindControl("Label13");       
command.CommandText = "INSERT INTO Transactions (etc,Date,etc)
VALUES (etc,@date,@etc)";        
command.Parameters.AddWithValue([snip]);       
command.Parameters.AddWithValue([snip]);        command.Parameters.AddWithValue("@date",
DateTime.Now.ToString());        
command.Parameters.AddWithValue([snip]);       
command.Parameters.AddWithValue([snip]);       
command.ExecuteNonQuery();       
con.Close();       
command.Dispose();       
return true;    }    protected
void Button2_Click(object sender, EventArgs e)   
{        TextBox TextBox1 =
FormView1.FindControl("TextBox1") as TextBox;       
bool retVal = ExecuteUpdate(Int32.Parse(TextBox1.Text));       
if (retVal)           
Response.Redirect("~/URL/EXTENSION.aspx");       
Insert();    }    private
void Insert()    {       
TextBox TextBox1 = FormView1.FindControl("TextBox1") as
TextBox;       
ExecuteInsert(TextBox1.Text);    }}  Thanks if someone can help!Jon 

View 1 Replies View Related

Conversion Failed When Converting Datetime From Character String

Jun 2, 2008

I am trying to write a SP in Query Analyzer before I start the code from a web form to acces it.
Here is the SQL:
-------------------------------------------
DECLARE @cReportGroups Varchar(500)DECLARE @StartDateRange DateTime
DECLARE @EndDateRange DateTime
SET @cReportGroups = '''VCCEddieBauer'',''VCCEddieBauerDirect'', ''VCCEddieBauerOrder'', ''VCCEddieBauerOvernight'', ''VCCEddieBauerSpanish'', ''VCCEddieBauerCustomerService'''
SET @StartDateRange = '09-16-2007'
SET @EndDateRange = '01-31-2008'
BEGIN
Declare @sql As Varchar(800)
Set @sql = 'SELECT ttalkacd, cName, dIntervalStart, cReportGroup' +
' FROM IAgentQueueStats ' +' WHERE dIntervalStart >= ' + @StartDateRange
---- ' AND dIntervalStart <= ' + EndDateRange  +
---- ' AND cReportGroup IN (' + @cReportGroups + ')' +
---- ' AND cHKey3 = ''*''' +
-- ' ORDER BY dIntervalStart' --+
---- ' COMPUTE SUM(ttalkacd)'
--Print(@sql)
exec (@sql)
END
-----------------------------------------------
Just trying to get the first >= filter working before I fill in the >= working to complete the date range logic.
But I keep getting this conversion error.
Why does SQL think that anything is a character string?All dates are declared as DateTime.I have tried a bunch of combinations like Convert(DateTime, @StartDateRange, 101).Nothing seems to work.

View 2 Replies View Related

Conversion Failed When Converting Datetime From Character String.

Mar 6, 2008



Good Morning:


I received the above error message when I try to convert a field to a date.

Here is the line of sql:

convert(datetime, cast(EligibilityEndDate as char(8)), 112) as EligibilityEndDate,


EligibilityEndDate is stored as an integer in our source system, so dates display 20080201.

Looks like the data is not a correct date.
If I just bring in the field as is, and load results into a text file or Access, I can't see the offending record.
The query returns around 320K records.

Is there another way of finding the invalid record(s)?

Any help appreciated.

Thanks.

Mike




View 4 Replies View Related

Help With Exception: Conversion Failed When Converting Datetime From Character String.

Mar 7, 2007

Hi,
I am trying to insert an entry into my database, but I keep on getting the following error: "Conversion failed when converting datetime from character string."  My query is a parameterized T-SQL query (i.e. "INSERT INTO blah (name, dob) VALUES (@name, '@dob')"), and I have initialized the SqlCommand object by doing:  sqlCmd.Parameters.AddWithValue("@name", "Captain America");
sqlCmd.Parameters.AddWithValue("@dob", birthdate.ToString("MM/dd/yyyy h:mm tt");

sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close(); 
 The dob field in the table 'blah' is a smalldatetime datatype, and in the code above, the birthdate object is a DateTime object. 
I can insert into my database using a normal T-SQL through Management Studio,
For example,  INSERT INTO blah (name, dob) VALUES ('Captain America', '11/27/1923 12:34 PM')
 But it doesn't work when I try doing it the way I have listed above.  It's really annoying because I don't know how to debug or if it is possible to debug the query.  So first off, I want to ask, does anyone know how why this exception is occuring?  Secondly, is it possible to debug the query? and if yes, how?  And finally, is there a way for me to extract the T-SQL query sent to the SQL Server with the parameters filled in their values? For example, after adding all parameters to the SqlCommand via sqlCmd.Parameters.AddWithValue(), can I get the T-SQL query that is sent to the server?

View 3 Replies View Related

Conversion Failed When Converting Datetime From Character String When Using Where Clause

Oct 22, 2007

I have written the following query to extract data splitting a text string into separate fields. This query works fine and returns results.



WITH a (company_id, user_id, project_id, customer_id, action, importdate, groupid, accountnumber, amount, notes, created, updated) AS

(

select

company_id,

user_id,

project_id,

customer_id,

action,

CAST(SUBSTRING(params, PATINDEX('%[ImportDate=%', params)+13, 19) AS datetime) AS ImportDate,

SUBSTRING(params, PATINDEX('%GroupID=%', params)+8, 1) AS GroupID,

SUBSTRING(params, PATINDEX('%AccountNo=%', params)+10, 7) AS AccountNumber,

CAST(SUBSTRING(substring(params, 0, len(params)), PATINDEX('%Amount=%', params)+7, 10) AS decimal(18,2)) AS Amount,

notes,

created,

updated

from


database.dbo.tablename

where

customer_id is not null and

PATINDEX('%GroupID=%', params) <> 0 and

PATINDEX('%ImportDate=%', params) <> 0 and

PATINDEX('%AccountNo=%', params) <> 0 and

PATINDEX('%Amount=%', params) <> 0

)

select

company_id,

user_id,

project_id,

customer_id,

action,

importdate,

DATEPART(year, importdate) AS importyear,

DATEPART(month, importdate) AS importmonth,

groupid,

accountnumber,

amount,

notes,

created,

updated

from

a




The problem arises when I try to do a WHERE on either the importyear or importmonth field.



WITH a (company_id, user_id, project_id, customer_id, action, importdate, groupid, accountnumber, amount, notes, created, updated) AS

(

select

company_id,

user_id,

project_id,

customer_id,

action,

CAST(SUBSTRING(params, PATINDEX('%[ImportDate=%', params)+13, 19) AS datetime) AS ImportDate,

SUBSTRING(params, PATINDEX('%GroupID=%', params)+8, 1) AS GroupID,

SUBSTRING(params, PATINDEX('%AccountNo=%', params)+10, 7) AS AccountNumber,

CAST(SUBSTRING(substring(params, 0, len(params)), PATINDEX('%Amount=%', params)+7, 10) AS decimal(18,2)) AS Amount,

notes,

created,

updated

from


database.dbo.tablename

where

customer_id is not null and

PATINDEX('%GroupID=%', params) <> 0 and

PATINDEX('%ImportDate=%', params) <> 0 and

PATINDEX('%AccountNo=%', params) <> 0 and

PATINDEX('%Amount=%', params) <> 0

)

select

company_id,

user_id,

project_id,

customer_id,

action,

importdate,

DATEPART(year, importdate) AS importyear,

DATEPART(month, importdate) AS importmonth,

groupid,

accountnumber,

amount,

notes,

created,

updated

from

a


where DATEPART(year, importdate) = 2007

I get


Conversion failed when converting datetime from character string.

but when I use ISDATE() to validate the importyear it returns nothing indicating that the actual importdate is a valid date. Can anyone help please?

Thanks

View 11 Replies View Related

Using UNION With 2 SELECT Statements Gives 'Conversion Failed When Converting Datetime From Character String.'

Apr 30, 2008



Good day all.

Let's see if I can stump you with this one.....




Code Snippet
SELECT Account.New_DistributorAccountNumber, Account.New_NameonBill, ActivityPointer.Subject, ActivityPointer.CreatedOn AS ExprX
FROM Account INNER JOIN
ActivityPointer ON Account.AccountId = ActivityPointer.RegardingObjectId
UNION
SELECT Account_1.New_DistributorAccountNumber AS Expr1, Account_1.New_NameonBill AS Expr2, ActivityPointer_1.CreatedOn AS Expr19,
ActivityPointer_1.Subject AS Expr20
FROM Account AS Account_1 INNER JOIN
Contact AS Contact_1 ON Account_1.AccountId = Contact_1.AccountId INNER JOIN
ActivityPointer AS ActivityPointer_1 ON Contact_1.ContactId = ActivityPointer_1.RegardingObjectId







gives the error mentioned above. Each select statement, when run separately, works fine. Any clues?

Thank you in advance

View 4 Replies View Related

CASE Throws Conversion Failed When Converting Datetime From Character String Exception

May 1, 2008



Hi All,

I have SQL query as:


SELECT CASE @sortcolumn

WHEN 'TYPE' THEN TYPE_TXT

WHEN 'DATE' THEN CHECKOUT_TS

WHEN 'ACCT' THEN ACCT_NBR

WHEN 'FIRST' THEN FIRST_NM

WHEN 'LAST' THEN LAST_NM

WHEN 'DAYS' THEN DATEDIFF(dd, CHECKOUT_TS, GETDATE())

ELSE DELIVER_ID END

FROM REQUEST

If @sortcolumn has 'DATE' or 'DAYS' it runs fine....any other value, I get an exception "Conversion failed when converting datetime from character string". All columns except CHECKOUT_TS are of type varchar.

Any help would be greatly appreciated.

Thanks,
Shashi

View 3 Replies View Related

Getting Server Error Syntax Error Converting The Nvarchar Value 'Sonoma' To A Column Of Data Type Int.

Apr 20, 2007

Hi, all
I'm getting this error at runtime when my page tries to populate a datagrid. Here's the relevant code.
First, the user selects his choice from a dropdownlist, populated with a sqldatasource control on the aspx side:<asp:SqlDataSource ID="sqlDataSourceCompany" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [PayrollCompanyID], [DisplayName] FROM [rsrc_PayrollCompany] ORDER BY [DisplayName]">
</asp:SqlDataSource>
 And the dropdown list's code:<asp:DropDownList ID="ddlPayrollCompany" runat="server" AutoPostBack="True" DataSourceID="sqlDataSourcePayrollCompany"
DataTextField="DisplayName" DataValueField="PayrollCompanyID">
</asp:DropDownList>
Then, I use the selectedindexchanged event to bind the data to the datagrid. Here's that code:
 1 Sub BindData()
2
3 Dim ds As New DataSet
4 Dim sda As SqlClient.SqlDataAdapter
5 Dim strSQL As String
6 Dim strCon As String
7
8 strSQL = "SELECT [SocialSecurityNumber], [Prefix], [FirstName], [LastName], [HireDate], [PayrollCostPercent], " & _
9 "[Phone], [BadgeNumber], [IsSupervisor], [SupervisorID], [IsUser], [IsScout] FROM [rsrc_Personnel] " & _
10 "WHERE ([PayrollCompanyID] = @PayrollCompanyID)"
11
12 strCon = "Data Source=DATASOURCE;Initial Catalog=DATABASE;User ID=USERID;Password=PASSWORD"
13
14 sda = New SqlClient.SqlDataAdapter(strSQL, strCon)
15
16 sda.SelectCommand.Parameters.Add(New SqlClient.SqlParameter("@PayrollCompanyID", Me.ddlPayrollCompany.SelectedItem.ToString()))
17
18 sda.Fill(ds, "rsrc_Personnel")
19
20 dgPersonnel.DataSource = ds.Tables("rsrc_Personnel")
21 dgPersonnel.DataBind()
22
23 End Sub
24

 
I'm assuming my problem lies in line 16 of the above code. I've tried SelectedItemIndex, SelectedItemValue too and get errors for those, as well.
What am I missing?
Thanks for anyone's help!
Cappela07

View 2 Replies View Related

Alias &#043; Stored Procedure Syntax Error

Jun 21, 2008

Hi,

Im new to this forum and new also to SQL SERVER Edition Express.

Im trying to creat stored procedure. My main problem is that I need to display an alias consisting of 2 fields in a combobox (VB.Net) using also an innerjoin. Can anyone help me find my mistake please


My code is here and the error is :
-----------------------------------------------------------
Msg 156, Level 15, State 1, Procedure LA_suppName, Line 16
Incorrect syntax near the keyword 'INNER'.

-----------------------------------------------------------

@supplierFID int,
@supplierID int,
@LANo nvarchar(15) OUTPUT,
@suppName nvarchar(MAX) OUTPUT

AS

BEGIN
SET NOCOUNT ON;

-- Insert statements for procedure here

SELECT tb_LA.LANo, tb_supplier.suppName AS OrderSupplier
INNER JOIN tb_supplier ON tb_LA.supplierFID=tb_supplier.supplierID
Order by tb_LA.LANo

END

------------------------------------------------------

Eventually I would need to use tb_LA.LANo and make a query to populate the tb_LABooks in another combobox on selectvaluechanged. Is this possible please???


Many thanks

View 5 Replies View Related







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