Converting Rrom Access Syntax To Sql Syntax

Sep 23, 2007


Ok I am tying to convert access syntax to Sql syntax to put it in a stored procedure or view..
Here is the part that I need to convert:

SELECT [2007_hours].proj_name, [2007_hours].task_name, [2007_hours].Employee,
IIf(Mid([task_name],1,3)='PTO','PTO_Holiday',
IIf(Mid([task_name],1,7)='Holiday','PTO_Holiday',
IIf(Mid([proj_name],1,9) In ('9900-2831','9900-2788'),'II Internal',
IIf(Mid([proj_name],1,9)='9900-2787','Sales',
IIf(Mid([proj_name],1,9)='9910-2799','Sales',
IIf(Mid([proj_name],1,9)='9920-2791','Sales',

)
)
)
)
) AS timeType, Sum([2007_hours].Hours) AS SumOfHours
from................

how can you convert it to sql syntax

I need to have a nested If statment which I can't do in sql (in sql I have to have select and from Together for example ( I can't do this in sql):
select ID, FName, LName
if(SUBSTRING(FirstName, 1, 4)= 'Mike')
Begin
Replace(FirstNam,'Mike','MikeTest')
if(SUBSTRING(LastName, 1, 4)= 'Kong')
Begin
Replace(LastNam,'Kong,'KongTest')
if(SUBSTRING(Address, 1, 4)= '1245')
Begin
.........
End
End

end




Case Statement might be the solution but i could not do it.






Your input will be appreciated

Thank you

View 5 Replies


ADVERTISEMENT

Syntax Error Converting The Varchar Value

Nov 4, 2004

Hey gurus!
I've got a stored proc I call to obtain user info from a table. I've used the same format (but is slightly different) for another stored proc which works. But this one gives me "Error: System.Data.SqlClient.SqlException: Syntax error converting the varchar value 'SELECT User_UserName AS Username, User_LastLogin AS LastLogin, User_DateCreated AS Created FROM Community_Users WITH(nolock) WHERE (User_CommunityID = '' to a column of data type int. at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream) at System.Data.SqlClient.SqlCommand.ExecuteReader() at ASP.Recent_Logins_ascx.BindGrid() at ASP.Recent_Logins_ascx.Page_Load(Object Src, EventArgs e) :"

Why is this stored proc converting my SQLStatement to type int???

Here's my stored proc:

CREATE PROCEDURE Community_RecentLogins
(
@CommunityID int,
@SortField nvarchar(75)
)
AS

-- Create a variable @SQLStatement
DECLARE @SQLStatement varchar(255)
SELECT @SQLStatement = 'SELECT User_UserName AS Username, User_LastLogin AS LastLogin, User_DateCreated AS Created FROM Community_Users WITH(nolock) WHERE (User_CommunityID = ''' + @CommunityID + ''') ORDER BY ' + @SortField

-- Execute the SQL statement
EXEC(@SQLStatement)


And here's the (relevant) code in the ascx:

Sub BindGrid()
Dim conPortal as SqlConnection = New SqlConnection(CommunityGlobals.ConnectionString)
Dim cmdGet as SqlCommand = new SqlCommand("Community_RecentLogins", conPortal)
cmdGet.CommandType = CommandType.StoredProcedure
cmdGet.Parameters.Add("@CommunityID", CommunityGlobals.CommunityID)
If SortField = String.Empty Then
cmdGet.Parameters.Add("@SortField", "User_LastLogin DESC")
Else
cmdGet.Parameters.Add("@SortField", SortField & " DESC")
End If
conPortal.Open()
Dim dr as SqlDataReader = cmdGet.ExecuteReader()
LoginGrid.DataSource = dr
LoginGrid.DataBind()
conPortal.Close()
End Sub

Property SortField() As String
Get
Dim o As Object = ViewState("SortField")
If o Is Nothing Then
Return String.Empty
End If
Return CStr(o)
End Get
Set(ByVal Value As String)
ViewState("SortField") = Value
End Set
End Property


Any help is appreciated! Thanks in advance...

View 2 Replies View Related

Syntax Error Converting Varchar To Int.

Jun 13, 2008

Hello,

I have table1
ID PATH
1 .166.184.185.186.

Need get data from table2 using PATH data from table1
select * from table2 where id in (
select Substring(replace(path,'.',','),2,Len(path)-2) from table1)
ERROR:
Syntax error converting the varchar value '166,184,185,186' to a column of data type int.

Any solution please.

Regard,
M.Z.

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

Transact SQL :: Converting Old Outer Join Syntax

Aug 22, 2015

I'm a Power Builder (PB) developer. I've migrated PB from 10 .5 to 12.5, and now I need to migrate the stored procedures from SQL Server 2005 to 2012 as well.I get a invalid expression error when I run the procedures in Power Builder. We have previously been using a lower database compatibility model in 2005, which allowed the procedures to work there. I have learned that =* is the old way to write right outer joins.

                            For example:
                            select  *
                            from    A
                            right outer join
                                    B
                           
[code]...

Is my approach correct, or do I need to add a WHERE condition to it? I don't have access to the production database to check. The development database is in SQL Server 2012 too, sO I will not be able to run the old version there to check.

View 8 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 Varchar Value '/' To A Column Of Datatype Int

Aug 31, 2007

Hi,
Can anyone please help me with the syntax for this query please. Error is "syntax error converting varchar value '/' to a column of datatype int"
Query:

Code:

select iCalls_Calls.Call_ID,iCalls_Calls.Requestor,Type,Scope,iCalls_Calls.Status_ID,iCalls_Status.Status_I D,
iCalls_Status.Status_Label,((select Count(*) from iCalls_Events where Call_ID = " & Session("Call_ID") & " ) + ' /' + (
select Count(*) from iCalls_Events where Call_ID = "& Session("Call_ID") & " and Events_Flag <> 0)) as Countrec from
((iCalls_Calls inner join iCalls_Status on iCalls_Calls.Status_ID=iCalls_Status.Status_ID ) inner join iCalls_Users on
iCalls_Calls.Requestor=iCalls_Users.User_ID) left outer join iCalls_Messages on iCalls_Calls.Call_ID=iCalls_Messages.Call_ID where Requestor='" & Session("User_ID") & "' AND iCalls_Calls.Status_ID <> 6 order by iCalls_Calls.Call_ID


Thanks...

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

Incorrect Syntax Near The Keyword CONVERT When The Syntax Is Correct - Why?

May 20, 2008

Why does the following call to a stored procedure get me this error:


Msg 156, Level 15, State 1, Line 1

Incorrect syntax near the keyword 'CONVERT'.




Code Snippet

EXECUTE OpenInvoiceItemSP_RAM CONVERT(DATETIME,'01-01-2008'), CONVERT(DATETIME,'04/30/2008') , 1,'81350'




The stored procedure accepts two datetime parameters, followed by an INT and a varchar(10) in that order.

I can't find anything wrong in the syntax for CONVERT or any nearby items.


Help me please. Thank you.

View 7 Replies View Related

Syntax Error Converting The Varchar Value '*' To A Column Of Data Type Int.

Oct 14, 2005

Hi,
This is my complete trigger.


ALTER TRIGGER DeleteTriggerC_Middleware_Exception ON dbo.C_Middleware_Exception AFTER DELETE AS
BEGIN
DECLARE @RowCount AS VARCHAR
SET @RowCount = @@ROWCOUNT

DECLARE @TableName_Deleted AS VARCHAR(50)
DECLARE @ErrorMsg_Deleted AS VARCHAR(255)
DECLARE @AddlErrMsg_Deleted AS VARCHAR(255)
DECLARE @SubjectArea_Deleted AS VARCHAR(25)
DECLARE @CHKPT_Deleted AS VARCHAR(10)

SELECT @TableName_Deleted = table_name , @ErrorMsg_Deleted = cast(error_msg AS varchar(255)) , @AddlErrMsg_Deleted = cast(addl_error_msg AS varchar(255)),
@SubjectArea_Deleted = cast(SUBJECT_AREA AS varchar(25)), @CHKPT_Deleted = cast(CHKPT AS varchar(255))FROM DELETED
--where subject_area = 'inventory'

UPDATE dbo.Error_Log SET No_Of_Occurance = No_Of_Occurance + @RowCount WHERE Table_Name = @TableName_Deleted
IF @@ROWCOUNT = 0
BEGIN
UPDATE dbo.Error_Log SET No_Of_Occurance = No_Of_Occurance + @RowCount WHERE @ErrorMsg_Deleted like Error_Msg and Subject_Area IS NULL and ChkPoint IS NULL
END
IF @@ROWCOUNT = 0
BEGIN
UPDATE dbo.Error_Log SET No_Of_Occurance = No_Of_Occurance + @RowCount WHERE @AddlErrMsg_Deleted like Addl_Error_Msg
END
IF @@ROWCOUNT = 0
BEGIN
UPDATE dbo.Error_Log SET No_Of_Occurance = No_Of_Occurance + @RowCount WHERE @ErrorMsg_Deleted like Error_Msg and Subject_Area = @SubjectArea_Deleted and ChkPoint = @CHKPT_Deleted
END

END


when i am executing the follwing query i am gettin systax error.

Query :delete from dbo.c_middleware_exception where subject_area = 'eap_room'

Error :
Server: Msg 245, Level 16, State 1, Procedure DeleteTriggerC_Middleware_Exception, Line 17
Syntax error converting the varchar value '*' to a column of data type int.


what could be the solution.

Thanks in advance
yvnsmca

View 1 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 The Varchar Value '10.136.20.20' To A Column Of Data Type Int.

Jul 20, 2005

I have an inventory database that Im trying to create a report out ofthe IP address are a lookup on a seperat table but I keep getting theabove error can I change the table row to something to fix this orwhat.SELECT i.INVENTORY_ITEM_ID AS [IP Address],i.HOST_NAME AS [ServerName], '' AS Flag, i.MEMO AS Comments, 'Seattle' AS City, 'Washington'AS State,CASE WHEN fv.value = 'EL EET1410' THEN '1111 3rdAve.' WHEN fv.value = 'EL WFL17' THEN '999 3rd Ave.' ELSE '' END AS[Address 1],' ' AS [Address 2], CASE WHEN fv.value = 'ELEET1410' THEN '1111' WHEN fv.value = 'EL WFL17' THEN '2222' ELSE ''END AS [Building ID],fv.VALUE AS Building, '98101' AS Zip,CASE WHEN fv.value = 'EL EET1410' THEN '14' WHENfv.value = 'EL WFL17' THEN '17' ELSE '' END AS [Computing FacilityLevel],CASE WHEN fv.value = 'EL EET1410' THEN '14' WHENfv.value = 'EL WFL17' THEN '17' ELSE '' END AS [Bldg Floor],CASE WHEN fv.value = 'EL EET1410' THEN 'C028'WHEN fv.value = 'EL WFL17' THEN 'C123' ELSE '' END AS WSPID,i.LOCATION_IN_FACILITY AS Location,i.SERIAL_NUMBER AS [Serial Number], i.ASSET_TAG AS [Asset Tag], ' ' AS[Second Asset Tag(s)],vv.VALUE AS Manufacture, mv.VALUE AS Model,'Yes' AS [Rack Mountable], rv.VALUE AS [Rack Units], 'DEV' AS [ServerEnviroment],lv.VALUE AS [Sever Type], ov.VALUE AS OS,CASE WHEN lv.value = 'Server - Intel Blade' THEN'Windows' WHEN lv.value = 'Server - Intel' THEN 'Windows' WHENlv.value = 'Server - Unix' THEN 'Unix'ELSE '' END AS [OS Type], '19x28' AS Footprint,ev.VALUE AS [Technical Owner of Server], 'N/A' AS [SLA Category],i.ON_BOARD_NIC_PORT_COUNT AS [NW Connectionquantity], 'Devlopment/Test Machine' AS [Application(s) Name],ev.VALUE AS [PW Contact],'N/A' AS RTO, 'N/A' AS RPO, 'No' AS [Is BoxClustered?], 'N/A' AS [Buisness Critical],CASE WHEN mv.value = 'Proliant DL580G1' THEN'90lbs' WHEN mv.value = 'Proliant DL360G2' THEN '85lbs' WHEN mv.value= 'Enterprise 220R' THEN'45lbs' ELSE '' END AS Weight,i.LAST_MODIFIED_DATE AS [Date of Last Install], 'No' AS [DedicatedCircuit]FROM dbo.INVENTORY_ITEM i LEFT OUTER JOINdbo.IP_TO_INVENTORY pv ON pv.IP_ADDRESS = i.INVENTORY_ITEM_IDLEFT OUTER JOINdbo.LOOKUP_VALUE lv ON lv.LOOKUP_VALUE_ID =i.DEVICE_TYPE_ID LEFT OUTER JOINdbo.LOOKUP_VALUE fv ON fv.LOOKUP_VALUE_ID =i.FACILITY_ID LEFT OUTER JOINdbo.LOOKUP_VALUE vv ON vv.LOOKUP_VALUE_ID =i.VENDOR_ID LEFT OUTER JOINdbo.LOOKUP_VALUE mv ON mv.LOOKUP_VALUE_ID =i.MODEL_ID LEFT OUTER JOINdbo.LOOKUP_VALUE ov ON ov.LOOKUP_VALUE_ID =i.SOFTWARE_VERSION_ID LEFT OUTER JOINdbo.LOOKUP_VALUE ev ON ev.LOOKUP_VALUE_ID =i.CHECKED_OUT_BY_ID LEFT OUTER JOINdbo.LOOKUP_VALUE rv ON rv.LOOKUP_VALUE_ID =i.U_HEIGHT_ID

View 2 Replies View Related

Syntax Error Converting The Varchar Value To A Column Of Data Type Int

Aug 29, 2007

SQL server 2000




Note : GRP_ID integer

declare @SchDnGRP VARCHAR(50)
SET @SchDnGRP='29,30'
SELECT USR_ID_ARY from AD_USR_GRP Where GRP_ID in(@SchDnGRP)




i got error like

Syntax error converting the varchar value '29,30' to a column of data type int.

if need any sql server Configuration requie, please advice to me

View 5 Replies View Related

Syntax Error Converting The Varchar Value 'a' To A Column Of Data Type Int

Feb 10, 2006

I have a table(tab1) with a column(col1) of type varchar. I insert a row with an integer value(1). And when i query the table using the sql, select col1 from tab1 where col1 = 1, it works fine.

But after i insert a varchar, say 'a' and then do the same query, i get an error message saying, "Syntax error converting the varchar value 'a' to a column of data type int.". Why is this so? Please reply.

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

Syntax Error Converting The Varchar Value 'email' To A Column Of Data Type Int.

Nov 4, 2005

Well I am doing a simple insert through a stored procedure..., but I am getting this error. In my table I have the UserID as a VARCHAR 100. I am storing from a textbox that will have number because its there email. But I am not converting anything. Do I need to convert in this scenario?? 
Server Error in '/pickem' Application.


Syntax error converting the varchar value 'johndoe@hotmail.com' to a column of data type int. 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 the varchar value 'johndoe@hotmail.com' to a column of data type int.Source Error:



Line 113:
Line 114: dbConnection.Open
Line 115: Dim Dr As System.Data.IDataReader = myCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
Line 116:
Line 117: Dim rowsAffected As Integer = 0
Here is the code:             Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(ConfigurationSettings.AppSettings("connString"))
             Dim myCommand as New SqlCommand("prcAddTeam", dbConnection)             myCommand.CommandType = CommandType.StoredProcedure
             myCommand.Parameters.Add("@UserID", SqlDbType.Varchar, 100).Value = TRIM(emailBox.Text)             myCommand.Parameters.Add("@TeamName", SqlDbType.Varchar, 40).Value = TRIM(teamBox.Text)             myCommand.Parameters.Add("@Address1", SqlDbType.Varchar, 50).Value = TRIM(addressBox.Text)             myCommand.Parameters.Add("@Address2", SqlDbType.Varchar, 50).Value = TRIM(address2Box.Text)             myCommand.Parameters.Add("@City", SqlDbType.Varchar, 50).Value = TRIM(cityBox.Text)             myCommand.Parameters.Add("@State", SqlDbType.Varchar, 30).Value = stateList1.SelectedItem.Value             myCommand.Parameters.Add("@Zip", SqlDbType.Varchar, 11).Value = TRIM(zipBox.Text)             myCommand.Parameters.Add("@FirstName", SqlDbType.Varchar, 50).Value = TRIM(firstNameBox.Text)             myCommand.Parameters.Add("@LastName", SqlDbType.Varchar, 50).Value = TRIM(lastnameBox.Text)
             dbConnection.Open             Dim Dr As System.Data.IDataReader = myCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
             Dim rowsAffected As Integer = 0
             dbConnection.OpenStored procedure:CREATE                  PROCEDURE prcAddTeam                 @UserID    VARCHAR(100)                ,@TeamName  VARCHAR(40)                ,@Address1  VARCHAR(50)                ,@Address2  VARCHAR(50)                ,@City      VARCHAR(50)                ,@State     VARCHAR(30)                ,@Zip       VARCHAR(11)                ,@FirstName VARCHAR(50)                ,@LastName  VARCHAR(50)   ASSET NOCOUNT ONDECLARE @ID   INTSET @ID = 0SELECT @ID = ISNULL((SELECT UserID from tblUserInfo      where UserID = @UserID),0)IF @ID = 0    BEGIN      INSERT INTO tblUserInfo (UserID,TeamName,Address1,Address2,City,State,Zip,FirstName,LastName,CreateDate)      VALUES(@UserID,@TeamName,@Address1,@Address2,@City,@State,@Zip,@FirstName,@LastName,GetDate())             SET @ID = @@IDENTITY      END

View 5 Replies View Related

Incorrect Syntax When There Appears To Be No Syntax Errors.

Dec 14, 2003

I keep receiving the following error whenever I try and call this function to update my database.

The code was working before, all I added was an extra field to update.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'WHERE'


Public Sub MasterList_Update(sender As Object, e As DataListCommandEventArgs)

Dim strProjectName, txtProjectDescription, intProjectID, strProjectState as String
Dim intEstDuration, dtmCreationDate, strCreatedBy, strProjectLead, dtmEstCompletionDate as String

strProjectName = CType(e.Item.FindControl("txtProjectName"), TextBox).Text
txtProjectDescription = CType(e.Item.FindControl("txtProjDesc"), TextBox).Text
strProjectState = CType(e.Item.FindControl("txtStatus"), TextBox).Text
intEstDuration = CType(e.Item.FindControl("txtDuration"), TextBox).Text
dtmCreationDate = CType(e.Item.FindControl("txtCreation"),TextBox).Text
strCreatedBy = CType(e.Item.FindControl("txtCreatedBy"),TextBox).Text
strProjectLead = CType(e.Item.FindControl("txtLead"),TextBox).Text
dtmEstCompletionDate = CType(e.Item.FindControl("txtComDate"),TextBox).Text
intProjectID = CType(e.Item.FindControl("lblProjectID"), Label).Text

Dim strSQL As String
strSQL = "Update tblProject " _
& "Set strProjectName = @strProjectName, " _
& "txtProjectDescription = @txtProjectDescription, " _
& "strProjectState = @strProjectState, " _
& "intEstDuration = @intEstDuration, " _
& "dtmCreationDate = @dtmCreationDate, " _
& "strCreatedBy = @strCreatedBy, " _
& "strProjectLead = @strProjectLead, " _
& "dtmEstCompletionDate = @dtmEstCompletionDate, " _
& "WHERE intProjectID = @intProjectID"

Dim myConnection As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("connectionstring"))
Dim cmdSQL As New SqlCommand(strSQL, myConnection)

cmdSQL.Parameters.Add(new SqlParameter("@strProjectName", SqlDbType.NVarChar, 40))
cmdSQL.Parameters("@strProjectName").Value = strProjectName
cmdSQL.Parameters.Add(new SqlParameter("@txtProjectDescription", SqlDbType.NVarChar, 30))
cmdSQL.Parameters("@txtProjectDescription").Value = txtProjectDescription
cmdSQL.Parameters.Add(new SqlParameter("@strProjectState", SqlDbType.NVarChar, 30))
cmdSQL.Parameters("@strProjectState").Value = strProjectState
cmdSQL.Parameters.Add(new SqlParameter("@intEstDuration", SqlDbType.NVarChar, 60))
cmdSQL.Parameters("@intEstDuration").Value = intEstDuration
cmdSQL.Parameters.Add(new SqlParameter("@dtmCreationDate", SqlDbType.NVarChar, 15))
cmdSQL.Parameters("@dtmCreationDate").Value = dtmCreationDate
cmdSQL.Parameters.Add(new SqlParameter("@strCreatedBy", SqlDbType.NVarChar, 10))
cmdSQL.Parameters("@strCreatedBy").Value = strCreatedBy
cmdSQL.Parameters.Add(new SqlParameter("@strProjectLead", SqlDbType.NVarChar, 15))
cmdSQL.Parameters("@strProjectLead").Value = strProjectLead
cmdSQL.Parameters.Add(new SqlParameter("@dtmEstCompletionDate", SqlDbType.NVarChar, 24))
cmdSQL.Parameters("@dtmEstCompletionDate").Value = dtmEstCompletionDate
cmdSQL.Parameters.Add(new SqlParameter("@intProjectID", SqlDbType.NChar, 5))
cmdSQL.Parameters("@intProjectID").Value = intProjectID

myConnection.Open()
cmdSQL.ExecuteNonQuery
myConnection.Close()

MasterList.EditItemIndex = -1
BindMasterList()


End Sub

Thankyou in advance.

View 3 Replies View Related

Which Is Faster? Conditional Within JOIN Syntax Or WHERE Syntax?

Mar 31, 2008

Forgive the noob question, but i'm still learning SQL everyday and was wondering which of the following is faster? I'm just gonna post parts of the SELECT statement that i've made changes to:

INNER JOIN Facilities f ON e.Facility = f.FacilityID AND f.Name = @FacilityName

OR

WHERE f.Name = @FacilityName


My question is whether or not the query runs faster if i put the condition within the JOIN line as opposed to putting in the WHERE line? Both ways seems to return the same results but the time difference between methods is staggering? Putting the condition within the JOIN line makes the query run about 3 times faster?

Again, forgive my lack of understanding, but could someone agree or disagree and give me the cliff-notes version of why or why not?

Thanks!

View 4 Replies View Related

MS Access SQL Syntax Error

Apr 22, 2004

There is a JOIN syntax error in this SQL, but my slow brain cannot figure out where. I tried to join two queries, which had been successful. Problem occurred when I added second left join. Can anyone help?

PARAMETERS pstrFinYear Text ( 255 ), pintAdjMonth Long;

SELECT A.BudgetLineID, A.BudgetLine, B.NumIsDevelopBusinessInternationally, B.NumIsDeeperParticipation, B.NumIsNewExporter, B.NumProjects, C.NumCompanies, A.KMISReportOrder
FROM ( tblkpBudgetLine AS A

LEFT JOIN

[SELECT BudgetLineID, FinancialYear, SUM(IsDevelopBusinessInternationally) AS NumIsDevelopBusinessInternationally, SUM(IsDeeperParticipation) AS NumIsDeeperParticipation, (-1*SUM(AdjustedNewExpMonth=pintAdjMonth)) AS NumIsNewExporter, COUNT(ProjectID) AS NumProjects
FROM qryBoardReport_Actuals
WHERE FinancialYear=pstrFinYear
AND AdjustedProjectStartMonth=pintAdjMonth
GROUP BY BudgetLineID, FinancialYear]. AS B
ON (A.BudgetLineID=B.BudgetLineID) AND (A.FinancialYear=B.BudgetLine)

LEFT JOIN

[SELECT Z.BudgetLineID, Z.FinancialYear, Z.AdjustedProjectStartMonth, COUNT(Z.Company) AS NumCompanies
FROM [SELECT DISTINCT qryBoardReport_Actuals.BudgetLineID AS BudgetLineID, qryBoardReport_Actuals.FinancialYear AS
FinancialYear, qryBoardReport_Actuals.AdjustedProjectStartMonth, qryBoardReport_Actuals.CompanyID as Company
FROM qryBoardReport_Actuals
WHERE FinancialYear=pstrFinYear
AND AdjustedProjectStartMonth=pintAdjMonth
GROUP BY qryBoardReport_Actuals.FinancialYear, qryBoardReport_Actuals.BudgetLineID, qryBoardReport_Actuals.AdjustedProjectStartMonth, qryBoardReport_Actuals.CompanyID]. AS Z
GROUP BY FinancialYear, BudgetLineID, AdjustedProjectStartMonth] as C

ON (A.BudgetLineID=C.BudgetLineID) and (A.FinancialYear=C.FinancialYear))


WHERE A.FinancialYear=pstrFinYear
ORDER BY A.KMISReportOrder;

View 8 Replies View Related

Access To SQL Server 7 Syntax Help

May 7, 2004

This runs in Access, but SQL Server 7 complains that BETWEEN is unrecognized. Can anyone help me? thanks


SELECT yearId, IIf(Date() BETWEEN [qrtOneStart] AND [qrtOneEnd],1, IIf(Date() BETWEEN [qrtTwoStart] AND [qrtTwoEnd], 2, IIf(Date() BETWEEN [qrtThreeStart] AND [qrtThreeEnd], 3, 4))) AS CurrentQrt, yearName
FROM tblYear

View 7 Replies View Related

Convert Access Query To Syntax?

Aug 21, 2013

I am trying to convert a code from access Db to sql code?

II(Left([dbo_ClaimLosstype].[dscr],4)="Liab","D_Liab","D_Property"),

View 4 Replies View Related

Incorrect Syntax Near... Fine In QA Not In Access

Apr 4, 2008

I created a couple of stored procedures. One of them (let's call it SP1) dumps information into a table and then calls another stored procedure (SP2) to put the info in a temp table in crosstab format. SP1 then displays the info from the temp table.

When I execute SP1 from Query Editor, everything works perfectly. No errors are returned and my data is displayed just as expected.

When I try to execute SP1 from MS Access's pass-through query, I get the following error:

[Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near ','.(#102)[Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'A'(#102)

I've found that the error occurs when the SP2 is called from within SP1. If it's working fine in Query Editor, shouldn't it work from MS Access? Any insights?

View 2 Replies View Related

Syntax To Access Database On Another Server

Feb 26, 2008

I know how to access different tables on the same server by prefixingthe table with the database name. Is there anyway to prefix theserver name to link two tables across servers? Thanks.

View 2 Replies View Related

Syntax For WHERE Clause For Access Database

Oct 17, 2006

I have used this query statement with a SQL Server 2005 database and need to use something similar with an Access database:

SELECT products.*, Category AS Expr1
FROM products
WHERE (Category = @Category)

When I test this in a table adapter there is no preview due to lack of parameter. I seem to recall that Access uses different syntax in the WHERE filter clause (i.e., not @). Can someone help me out with this?

View 3 Replies View Related

UPDATE Into JOINed Table - Access Vs. SQL Server Syntax

Sep 13, 2007

I am trying to get a SQL statement to work with both Access 2000 and SQL Server 2000.

The statement that works in SQL Server is:

---
UPDATE [myTable2]

SET
[myTable2].[FieldA] = 'Hello',
[myTable2].[FieldB] = 2,
[myTable2].[FieldC] = 'xxx',
[myTable2].[FieldD] = 0

FROM [myTable1] INNER JOIN
(myTable2 INNER JOIN [myTable3]
ON [myTable2].[FieldX]=[myTable2].[FieldY])
ON [myTable1].[FieldZ]=[myTable2].[FieldY]

WHERE ([myTable2].[FieldY]=1)
And ([myTable3].[FieldZ]='xxx');
---


(names have been changed to protect the innocent)


The statement that works in Access is:

---
UPDATE [myTable1] INNER JOIN
(myTable2 INNER JOIN [myTable3]
ON [myTable2].[FieldX]=[myTable2].[FieldY])
ON [myTable1].[FieldZ]=[myTable2].[FieldY]

SET
[myTable2].[FieldA] = 'Hello',
[myTable2].[FieldB] = 2,
[myTable2].[FieldC] = 'xxx',
[myTable2].[FieldD] = 0

WHERE ([myTable2].[FieldY]=1)
And ([myTable3].[FieldZ]='xxx');
---


It seems that neither will accept the other format. Can anyone suggest how I can rearrange the statement so that it works in both?

View 2 Replies View Related

Integration Services :: Correct Syntax To Access A Variable

Sep 30, 2015

I am having trouble finding the correct syntax to access a variable. I have a variable defined in the Variables window: The variable name is formatedDate. The DataType is String.

I am successfully setting the value of the variable in a Execute SQL Task. The SQL is as follows:

SELECT LEFT(CONVERT(VARCHAR, MAX(ReportDate), 120), 10) as formatedDate
from DimReportDates

The Result Set is set to “Single Row” and properly set up. 

No problem so far. I can see with a watch that the variable has the correct value, something like:

‘2015-09-30’

Now, in a subsequent step, a Data Flow Task, I want to access the variable. Actualy it is in the SQL statement of a OLE DB source in the Data Flow… I have the following:

Declare @sDate smalldatetime
SELECT @sDate = xxxxx

I have tried several things substituting xxxxx above, but nothing seems to work. One variation was

 @[User::formatedDate])

 Another was

((DT_WSTR, 10) @[User::formatedDate]).

I think I’m close, but just can’t get it. What is the correct syntax.

View 4 Replies View Related







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