take numeric values from text - sql

i have values such as
1st
2nd
3rd
4th
how would use an sql statement to just take the numbers and put them in a table so that i just have 1,2,3,4
right now i am trying this code below
DoCmd.RunSQL "UPDATE DEDValidation LEFT JOIN ReqInput ON DEDValidation.[Plan Code] = ReqInput.[Plan Code] SET DEDValidation.[Expected Plan Effective Day] =ReqInput.[Start Day] WHERE DEDValidation.[DED Row Found] = 'Yes'"
DoCmd.RunSQL "Update DEDValidation Set DEDValidation.[Expected Plan Effective Day] = REPLACE(DEDValidation.[Expected Plan Effective Day], '*st', '') WHERE DEDValidation.[Expected Plan Effective Day] LIKE '*st'"
the first line imports the code and the second is supposed to replace the letters 'st' with a blank, but its not working

Try this. Change the Replace function for this:
REPLACE(DEDValidation.[Expected Plan Effective Day], 'st', '')
Hope it helps you!

Related

SQL Execution error while running parameter query

Can somebody tell me what i have done wrong in my Parameter query as it does not work?
Basically my intention is to create a search result and display it using DataGridView.
These errors appear when I click 'Execute Query' on query builder window.
Below is the SQL Statement
SELECT Products.[Product Name], Products.[Product code], [Brands For Sales].[Brand Name], [Main Group].[Group Name], Category.[Catogory Name], SubCatogory.[SubCatogory Name]
FROM (((((Products INNER JOIN
Category ON Products.[Category-ID] = Category.ID)
INNER JOIN
[Brands For Sales] ON Products.[Brand Name] = [Brands For Sales].ID) INNER JOIN
[Main Group] ON Products.[Group-ID] = [Main Group].ID AND Category.[Group-ID] = [Main Group].ID) INNER JOIN
Category Category_1 ON Products.[Category-ID] = Category_1.ID AND [Main Group].ID = Category_1.[Group-ID]) INNER JOIN
SubCatogory ON Products.[SubCategory-ID] = SubCatogory.ID AND Category.ID = SubCatogory.[Catogory-ID] AND Category_1.ID = SubCatogory.[Catogory-ID])
WHERE (Products.[Product Name] LIKE '%' + #Searchbox + '%')
If I remember correctly, Query Builder doesn't support named parameters even for SQL Server, never mind Access. Replace each of your #ParameterName placeholders with ? and you should be good to go.
EDIT:
The only thing that changes when using positional parameters rather than named parameters (other then the fact that you must add them in the same order as they appear in the SQL, which you should do anyway) is that you cannot reuse a parameter. That means that you might have to pass the same value twice. For instance, if you used this SQL with named parameters:
SELECT *
FROM MyTable
WHERE Column1 = #SomeValue
OR Column2 = #SomeValue
and then you passed a single value to a single parameter to be used twice in the SQL code, you would change the SQL to this with positional parameters:
SELECT *
FROM MyTable
WHERE Column1 = ?
OR Column2 = ?
and then your command would have two parameters and you would pass the same value to both of them. That's exactly what everyone already does with Access even if they do name their parameters, because the Jet and ACE OLE DB providers ignore those names and use positions anyway.

CASE or IF in AND statement

I've got a query with a bunch of AND statements. Now when a variable is set, I want to use a specific AND statement. But when it's empty or NULL I don't want that statement. I've found some things with IF and CASE but I can't get it done :(
I Want something like this
SELECT *
FROM table
WHERE [Statement1]
IF #Location IS NOT NULL OR <> ''
BEGIN
AND [SBC Live 2$Sales Shipment Line].[Location _ Sector No_] = #Location
END
Maybe someone can help me?
Thnanks in advance!
This should work for you:
SELECT *
FROM table
WHERE [Statement1] AND (ISNULL(#Location,'') = '' OR [SBC Live 2$Sales Shipment Line].[Location _ Sector No_] = #Location)
So in the end, either #Location is null/blank, or it matches the [SBC Live 2$Sales Shipment Line].[Location _ Sector No_]
Note: In your pseudo-code, you have OR in the IF check, but based off what you wrote previously, I assume you're looking for AND there.

Comparing Date Values in Access - Data Type Mismatch in Criteria Expression

i'm having an issue comparing a date in an access database. basically i'm parsing out a date from a text field, then trying to compare that date to another to only pull newer/older records.
so far i have everything working, but when i try to add the expression to the where clause, it's acting like it's not a date value.
here's the full SQL:
SELECT
Switch(Isdate(TRIM(LEFT(bc_testingtickets.notes, Instr(bc_testingtickets.notes, ' ')))) = false, 'NOT ASSIGNED!!!') AS [Assigned Status],
TRIM(LEFT(bc_testingtickets.notes, Instr(bc_testingtickets.notes, ' '))) AS [Last Updated Date],
bc_testingtickets.notes AS [Work Diary],
bc_testingtickets.ticket_id,
clients.client_code,
bc_profilemain.SYSTEM,
list_picklists.TEXT,
list_picklists_1.TEXT,
list_picklists_2.TEXT,
list_picklists_3.TEXT,
bc_testingtickets.createdate,
bc_testingtickets.completedate,
Datevalue(TRIM(LEFT([bc_TestingTickets].[notes], Instr([bc_TestingTickets].[notes], ' ')))) AS datetest
FROM list_picklists AS list_picklists_3
RIGHT JOIN (list_picklists AS list_picklists_2
RIGHT JOIN (list_picklists AS list_picklists_1
RIGHT JOIN (bc_profilemain
RIGHT JOIN (((bc_testingtickets
LEFT JOIN clients
ON
bc_testingtickets.broker = clients.client_id)
LEFT JOIN list_picklists
ON
bc_testingtickets.status = list_picklists.id)
LEFT JOIN bc_profile2ticketmapping
ON bc_testingtickets.ticket_id =
bc_profile2ticketmapping.ticket_id)
ON bc_profilemain.id =
bc_profile2ticketmapping.profile_id)
ON list_picklists_1.id = bc_testingtickets.purpose)
ON list_picklists_2.id = bc_profilemain.destination)
ON list_picklists_3.id = bc_profilemain.security_type
WHERE ( ( ( list_picklists.TEXT ) <> 'Passed'
AND ( list_picklists.TEXT ) <> 'Failed'
AND ( list_picklists.TEXT ) <> 'Rejected' )
AND ( ( bc_testingtickets.ticket_id ) <> 4386 ) )
GROUP BY bc_testingtickets.notes,
bc_testingtickets.ticket_id,
clients.client_code,
bc_profilemain.SYSTEM,
list_picklists.TEXT,
list_picklists_1.TEXT,
list_picklists_2.TEXT,
list_picklists_3.TEXT,
bc_testingtickets.createdate,
bc_testingtickets.completedate,
DateValue(TRIM(LEFT([bc_TestingTickets].[notes], Instr([bc_TestingTickets].[notes], ' '))))
ORDER BY Datevalue(TRIM(LEFT([bc_TestingTickets].[notes], Instr([bc_TestingTickets].[notes], ' '))));
the value i'm trying to compare against a various date is this:
DateValue(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' '))))
if i add a section to the where clause like below, i get the Data Type Mismatch error:
WHERE DateValue(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' ')))) > #4/1/2012#
i've even tried using the DateValue function around the manual date i'm testing with but i still get the mismatch error:
WHERE DateValue(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' ')))) > DateValue("4/1/2012")
any tips on how i can compare a date in this method? i can't change any fields in the database, ect, that's why i'm parsing the date in SQL and trying to manipulate it so i can run reports against it.
i've tried googling but nothing specifically talks about parsing a date from text and converting it to a date object. i think it may be a bug or the way the date is being returned from the left/trim functions. you can see i've added a column to the end of the SELECT statement called DateTest and it's obvious access is treating it like a date (when the query is run, it asks to sort by oldest to newest/newest to oldest instead of A-Z or Z-A), unlike the second column in the select.
thanks in advance for any tips/clues on how i can query based on the date.
edit:
i just tried the following statements in my where clause and still getting a mismatch:
CDate(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' ')))) > #4/1/2012#
CDate(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' ')))) >
CDate("4/1/2012") CDate(DateValue(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[‌​notes],' '))))) > #4/1/2012#
i tried with all the various combinations i could think of regarding putting CDate inside of DateValue, outside, ect. the CDate function does look like what i should be using though. not sure why it's still throwing the error.
here's a link to a screenshot showing the results of the query http://ramonecung.com/access.jpg. there's two screenshots in one image.
You reported you get Data Type Mismatch error with this WHERE clause.
WHERE DateValue(Trim(Left([bc_TestingTickets].[notes],
InStr([bc_TestingTickets].[notes],' ')))) > #4/1/2012#
That makes me wonder whether [bc_TestingTickets].[notes] can ever be Null, either because the table design allows Null for that field, or Nulls are prohibited by the design but are present in the query's set of candidate rows as the result of a LEFT or RIGHT JOIN.
If Nulls are present, your situation may be similar to this simple query which also triggers the data type mismatch error:
SELECT DateValue(Trim(Left(Null,InStr(Null,' '))));
If that proves to be the cause of your problem, you will have to design around it somehow. I can't offer a suggestion about how you should do that. Trying to analyze your query scared me away. :-(
It seems like you are having a problem with the type conversion. In this case, I believe that you are looking for the CDate function.
A problem might be the order of the date parts. A test in the Immediate window shows this
?cdate(#4/1/2012#)
01.04.2012
?cdate(#2012/1/4#)
04.01.2012
Write the dates backwards in the format yyyy/MM/dd and thus avoiding inadverted swapping of days and months!
DateValue("2012/1/4")
and
CDate(#2012/1/4#)

LINQ to SQL selecting records and converting dates

I'm trying to select records from a table based on a date using Linq to SQL. Unfortunately the date is split across two tables - the Hours table has the day and the related JobTime table has the month and year in two columns.
I have the following query:
Dim qry = From h As Hour In ctx.Hours Where Convert.ToDateTime(h.day & "/" & h.JobTime.month & "/" & h.JobTime.year & " 00:00:00") > Convert.ToDateTime("01/01/2012 00:00:00")
This gives me the error "Arithmetic overflow error converting expression to data type datetime."
Looking at the SQL query in SQL server profiler, I see:
exec sp_executesql N'SELECT [t0].[JobTimeID], [t0].[day], [t0].[hours]
FROM [dbo].[tbl_pm_hours] AS [t0]
INNER JOIN [dbo].[tbl_pm_jobtimes] AS [t1] ON [t1].[JobTimeID] = [t0].[JobTimeID]
WHERE (CONVERT(DateTime,(((((CONVERT(NVarChar,[t0].[day])) + #p0) + (CONVERT(NVarChar,COALESCE([t1].[month],NULL)))) + #p1) + (CONVERT(NVarChar,COALESCE([t1].[year],NULL)))) + #p2)) > #p3',N'#p0 nvarchar(4000),#p1 nvarchar(4000),#p2 nvarchar(4000),#p3 datetime',#p0=N'/',#p1=N'/',#p2=N' 00:00:00',#p3='2012-01-31 00:00:00'
I can see that it's not passing in the date to search for correctly but I'm not sure how to correct it.
Can anyone please help?
Thanks,
Emma
The direct cause of the error may have to do with this issue.
As said there, the conversions you use are a very inefficient way to build a query. On top of that, it is inefficient because the expressions are not sargable. I.e. you are using a computed value from database columns in a comparison which disables the query analyzer to use indexes to jump to individual column values. So, you could try to fix the error by doctoring the direct cause, but I think it's better to rewrite the query in a way that only the single column values are used in comparions.
I've worked this out in C#:
var cfg = new DateTime(12,6,12);
int year = 12, month = 6, day = 13; // Try some more values here.
// Date from components > datetime value?
bool gt = (
year > cfg.Year || (
(year == cfg.Year && month > cfg.Month) || (
year == cfg.Year && month == cfg.Month && day > cfg.Day)
)
);
You see that it's not as straightforward as it may look at first, but it works. There are much more comparisons to work out, but I'm sure that the ability to use indexes will easily outweigh this.
A more straightforward, but not sargable, way is to use sortable dates, like 20120101 and compare those (as integers).

Using iif clause in Ms Access for a column with "Yes/No" Data Type

I have a column called DayShift in a table which is of Yes/No data type (Boolean). The result Output I want is: if the value is true, display "Day" else display night.
I have tried the following:
SELECT iif(DayShift=Yes,"Day","Night") as Shift FROM table1;
SELECT iif(DayShift,"Day","Night") as Shift FROM table1;
SELECT iif(DayShift=True,"Day","Night") as Shift FROM table1;
SELECT iif(DayShift=1,"Day","Night") as Shift FROM table1;
But none of the above work. It just gives me a list of blank check boxes in the output datasheet window. I am using Ms Access 2003. Any help appreciated.
Update:
After a bit of research that the yes/no data type in Ms Access 2003 cannot handle null values appropriately. Hence, the error. Check this link for details.
Update 2
Real Query with the joins. Didnt mention it since i though the information provided above would work.
SELECT tblovertime.contfirstname AS [First Name],
tblovertime.contlastname AS [Last Name],
tblovertime.employeenumber AS [Employee Number],
tblsignup.thedate AS [Sign Up Date],
Iif([tblOvertime.DayShift] =- 1, "Day", "Night") AS shift,
(SELECT Mid(MIN(Iif(sector = 1, "," & sector, NULL)) & MIN(
Iif(sector = 2, "," & sector, NULL)) & MIN(
Iif(sector = 3, "," & sector, NULL)) & MIN(
Iif(sector = 4, "," & sector, NULL)), 2) AS concat
FROM tblempsectorlist
WHERE tblempsectorlist.empnum = tblsignup.employeenumber
GROUP BY empnum) AS sectors,
tblovertime.timedatecontact AS [Date Contacted],
tblovertimestatus.name AS status
FROM (tblsignup
INNER JOIN tblovertime
ON ( tblsignup.thedate = tblovertime.otdate )
AND ( tblsignup.employeenumber = tblovertime.employeenumber ))
INNER JOIN tblovertimestatus
ON Clng(tblovertime.statusid) = tblovertimestatus.statusid
WHERE (( ( tblsignup.thedate ) ># 1 / 1 / 2011 # ))
ORDER BY tblsignup.thedate;
Your second one has it right
SELECT iif(DayShift,"Day","Night") as Shift FROM table1;
I suggest trying the following to see what's actually being evaluated
SELECT iif(DayShift,"Day","Night") as Shift, DayShift FROM table1;
You could equally do
SELECT iif(DayShift = -1,"Day","Night") as Shift FROM table1;
Since MS Access is storing true as -1 and false as 0 (it's not as intuitive as true = 1, but it's probably faster to evaluate in twos-compliment)
-- edit --
Since you appear to be using a join, which can result in Nul's for Yes/No's, use the nz() function.
select iff(nz(DayShift, 0), "Day","Night") as Shift FROM table1;
When DayShift comes out null, this will return 0 (false/no) as a result instead.
This one might be stupid, but ....
In case you have some Null values in the DayShift field, Access will not be able to evaluate the formula. You could write your test this way:
iif(Nz(DayShift,0)=-1,"Day","Night")
I ran the following query successfully:
SELECT IIf([Table1]![isDayShift]=True,"Day","Night") AS Shift
FROM Table1;
I built this in Access 2007 (sorry, I didn't have a copy of 2003 lying around). The only difference I saw was that it gave the full path to the field instead of just the field name. However, that shouldn't be an issue. If it is giving you checkboxes, it would seem that it is not seeing this field as a text field but rather as a checkbox field still.
Bottom line is the above query should work.
You are binding to "DayShift" rather then the derived "Shift" in the form.
The 3rd query (=True) show when run in isolation should show Day/Night.
The Access database engine (ACE, Jet, whatever) has a clever/stupid feature that allows an expression in the SELECT clause to refer to an AS clause ("column alias") in the same SELECT clause if that AS clause is to the left of the expression. This makes it easy to test expressions with test data without using a table at all (assuming ANSI-92 Query Mode, I think) e.g. try executing any of the following statements individually: all should work and produce the expected result:
SELECT CBOOL(TRUE) AS DayShift,
IIF(DayShift = TRUE, 'Day', 'Night') AS Shift;
SELECT CBOOL(FALSE) AS DayShift,
IIF(DayShift = TRUE, 'Day', 'Night') AS Shift;
SELECT NULL AS DayShift,
IIF(DayShift = TRUE, 'Day', 'Night') AS Shift;
SELECT CBOOL(TRUE) AS DayShift,
IIF(DayShift, 'Day', 'Night') AS Shift;
SELECT CBOOL(FALSE) AS DayShift,
IIF(DayShift, 'Day', 'Night') AS Shift;
SELECT NULL AS DayShift,
IIF(DayShift, 'Day', 'Night') AS Shift;