SQL - MS Access - search text between two known text string - sql

I'm looking to extract 3 text part of below string..
Requested Ship Date: 05/31/2016 Please charge shipping to: ups 1234 PO Number: po 1234
05/31/2016
ups 1234
po 1234
Knowing that Requested Ship Date: and Please charge shipping to: and PO Number: never change.. but the character length of the second and third can change..
I'm not very good in SQL Access. I know that in Excel it would be easy with the right and find option.. but in Access?
Is there a way to find what's right of each : and then subtract the result?
Any ideas that can help me?

Using Split() it would be easy to split the input string into pieces and extract the pieces you need. Here is an example from the Access Immediate window.
YourString = "Requested Ship Date: 05/31/2016 Please charge shipping to: ups 1234 PO Number: po 1234"
astrPieces = Split(YourString, " ")
? astrPieces(3)
05/31/2016
? astrPieces(9)
1234
? astrPieces(13)
1234
However, Split() can't be used directly in Access SQL. But, since your query will only be run within an Access session, you could create a VBA function which uses Split() and use that function in your query.
Here is an Immediate window example of such a function in action.
? GetShipData(YourString, "date")
05/31/2016
? GetShipData(YourString, "ups")
1234
? GetShipData(YourString, "po")
1234
So your query could be similar to this:
SELECT
GetShipData([YourFieldName], "date") AS ship_date,
GetShipData([YourFieldName], "ups") AS ups,
GetShipData([YourFieldName], "po") AS po
FROM YourTable;
Here is the function I tested in the Immediate window example above:
Public Function GetShipData(ByVal pInput As String, ByVal pWhichItem As String) As String
Dim astrPieces() As String
Dim strReturn As String
astrPieces = Split(pInput, " ")
Select Case pWhichItem
Case "date"
strReturn = astrPieces(3)
Case "ups"
strReturn = astrPieces(9)
Case "po"
strReturn = astrPieces(13)
Case Else
strReturn = "fail" '<- figure out what you want here
End Select
GetShipData = strReturn
End Function
You will probably want to refine that function in case any of your input strings don't match the pattern of your question's sample string.

Related

SQL: Compare Date Range in a String text field

I have an MS Access db. I am writing an application in C# to access it. I have a field "FileName" of type "Short Text in MS Access. Data in FileName field is like "Test 11-12-2004 15.11.15".
Using a Date Range, I got to search records based on FileName field. I am not able to get - How do I compare the date of this format and retrieve the records ? FileName is a Text type and date is a substring of it. Retrieving only the date part and comparing with >= beginDate && <= endDate seems like a puzzle to me.
Can anyone suggest how do I write SQL query to perform this date range comparision and retrieve those records - "Select * from TestHead where FileName......" ????
Any help is appreciated.
Thanks a lot,
In your C# code, as you are going through the records, I'd split the string like this:
char[] delimiters = {' '};
string[] FileNameParts = FileName.Split(delimiters);
This will result in an array FileNameParts, the second element of which will contain the date, which you can convert to an actual date for use in the query:
DateTime FileNameDate = Convert.ToDateTime(FileNameParts(1))
Something along the lines of:
sSQL = "SELECT * FROM Table WHERE " & beginDate & " <= " & FileNameDate
I see this as preferable to adding a column to your table that contains the date substring of the FileName field, because then you constantly need to be updating that column whenever existing records are modified or new records are added. That means more clutter on the C# side, or an UPDATE query on the Access side which at least needs to get called periodically. Either way it would be more communication with the database.

Store MonthName() function in a string variable

First question here so go easy on me!
I am new to Visual Basic (but not programming) and I am having trouble on a project I am working on for a local organization.
I have a button that runs a query that contains a single "SELECT ... INTO ... " statement. This statement also looks for every record where the field RecievedBoxToday is equal to "Yes". Here is the code that is working just fine:
SELECT * INTO RENAME_THIS_TABLE
FROM [DATABASE ZERO]
WHERE (([DATABASE ZERO].RecievedBoxToday)=Yes);
Now here is the problem (besides the fact that Received is spelled wrong): This code will be ran every month, but the table (RENAME_THIS_TABLE) is over-written every time the button is clicked. I would like to have permanent data for every month so my solution is to rename the RENAME_THIS_TABLE table to MONTHNAME_YEAR where MONTHNAME is the name of the month (January or December) and YEAR is the current year (2015). I thought I could go about doing this with the MonthName() function, which works just fine, but I want to be able to store this month name into a string to be concatenated with the year (also a string). Afterwords this string will replace RENAME_THIS_TABLE.
My code for this that doesn't seem to work is:
dim Month As String
dim Year As String
MonthName(Month(Date()), False) As Month
Year(Date()) As Year
dim NewName As String = Month + "_" + Year
After this I'm not sure where to go as far as taking this new string variable and inserting into the SQL code, where it will replace RENAME_THIS TABLE.
How can I make this work? Can I make this work? If it matters, I am using VBA with Microsoft Access 2013. Any help is greatly appreciated!
Don't use Month and Year as variable names. Those are reserved (function) names in VBA. Also, as a shortcut, you can just use the Format() function to format your date string:
Dim strNewName As String
strNewName = Format(Date, "mmmm_yyyy") ' => "August_2015"
If your SQL statement is stored in a separate string, you can just concatenate your new table name into your string:
Dim strSql As String
strSql = "SELECT * INTO " & strNewName & " FROM [DATABASE ZERO] WHERE (([DATABASE ZERO].RecievedBoxToday)=Yes);"

SSRS Format a multi-value field

I have a number field in my ssrs report that has multiple values separated by a comma. I want to convert the number to currency but I get an error when the field has more than on value. I'm converting the text box to currency and added the (*) operator to multiply by .01 so my numbers are not inflated. I'm sure the comma is what causing the error as BIDS is expecting a number, but I'm not sure how to write the expression so that it only modifies the numbers in the string.
=Fields!field_A.Value * .01
Field
Number1 = converts to currency($Number1)
Number1, Number2 = #Error
number1, number2, number3 = #error
You can use embedded code in the report to do the processing of the string. This allows you to use the full VB.NET language. From the report menu in SSRS select Report Properties and select the Code section on the left. (This is in VS2010, I'm not sure what version of SSRS you're building in.)
Then you can use a VB.NET function like the one below to do the actual string processing. I'm not sure exactly how you want the output so you'll want to read the MSDN page on the FormatNumber() VB.NET function.
Function ConvertCashString(orig As String)
Dim newString As String = ""
For Each s As String In orig.Split(",")
Dim parsedString As Double
If (Double.TryParse(s, parsedString)) Then
newString += "$" + FormatNumber(parsedString * 0.01, 2, TriState.True, TriState.UseDefault, TriState.False) + ", "
End If
Next
Return newString
End Function
Then in the report itself you can call the function like so:
=Code.ConvertCashString(Fields!dbString.Value)
You should also read the MSDN page: Add Code to a Report (SSRS)

does SSRS have a limit on number of fields in the dataset?

I have a data set:
select * from table1 --approximately 100 fields
join table2
on...
join table3
on...
The query works when I test it in SSMS.
However, when I try to run a report with this query as the dataset, I am getting:
I thought that perhaps I'm incorrectly capturing the names of the fields, so instead of doing select * i did select field1, field2...field100 but still getting the same result.
What am I doing wrong?
Please note that I have indeed made sure that all the field names are unique by doing a unique filter in excel.
I ran into the same problem. This was my solution.
1)First test your Reporting boundaries, try to determine the maximum amount of fields you can display.
2)Take your main report and make it a sub report.
3)Pass the remaining values through parameters as a concatenated string
4)Use your new sub-report to parse the parameters string.
Here is some VB code to help. Paste this in your report properties cod section.
'***************************************************************************************************************************
Public Function ListToString(myList As String, Delimiter As String, Optional index As Integer = 0) As String
'-----------------------------------------------------------------------------------
'Purpose:
'----This function splits a list and allows one to access the split list like a programmable array
'Description:
'----Input:
'--------myList: String containing the list created in SSRS
'--------Delimiter: what you used to seperate/ delimit each element
'--------index: the index you want you access
'----Output:
'--------ReturnString: returns Name in the format of "FirstName LastName"
'Version Control log: (Date - Name: Description)
'----xx/xx/xxxx Adrian Williams Creation of function
'-----------------------------------------------------------------------------------
Dim returnString As String = ""
Dim myArray As String()
myArray = myList.split(delimiter)
returnString = trim(myArray(index))
Return returnString
End Function
'***************************************************************************************************************************

Checking for date overlap across multiple date range objects

I have several records in a database that have Start and End Dates
09/15/2011 - 09/30/2011
10/15/2011 - 10/22/2011
11/01/2011 - 11/15/2011
When user stores a record, I need to make sure dates don't overlap.
My simple code checks date ranges within a specific record (e.g. user enters 9/16/2011 or 10/21/2011, I throw an exception.)
But, on the slim chance a user gets creative (e.g. 10/14/2011 - 10/23/2011 or even 10/14/2011 to 11/16/2011), now they have circumvented my check.
BTW, the user could enter 10/14/2011 to 10/23/2011 if they were editing the record that contained values 10/15/2011 - 10/22/2011.
So, I'm trying to solve this riddle with a linq query. However, what I have isn't working exactly right.
UPDATE Nevermind about code not working. While trying to provide an example to expand on Miika's repsonse, I found my answer. So, giving credit to Miika for pointing me in the right direction and posting my working code below:
Here's my code:
Private Sub CheckForOverlap(myMonth As Messages.MyMonth)
Dim am As New MyMonth()
Dim amCollection As Messages.MyMonthCollection
Dim overlappingMyMonthDate As Boolean = False
Dim sErrorMsg As String = ""
'...non-applicable code omitted
Dim query = From s In amCollection _
Let s1 As MyMonth = CType(s, MyMonth) _
Where s1.AttendanceMonthID <> attendanceMonth.AttendanceMonthID And _
(CDate(attendanceMonth.StartDate) < CDate(s1.StartDate) And CDate(attendanceMonth.EndDate) > CDate(s1.EndDate)) _
Select s1
If query.Count > 0 Then
sErrorMsg = "Dates entered surround another entry"
End If
If overlappingMyMonthDate Then
Throw New Exception(sErrorMsg)
End If
End Sub
End Class
It all came down a LINQ query.
Do you need to do it in code or would SQL be an option? If the data is in a database, you could use the following query to check for overlaps.
SELECT COUNT(*)
FROM Table1
WHERE Table1.StartDate < 'endCheckDate'
AND Table1.EndDate > 'startCheckDate'
This will return a count of the number of overlaps found. 'endCheckDate' and 'startCheckDate' are your new query values (in date format). If your data is in a object collection in memory, then you could use LINQ. If you need help with a LINQ statement, let me know.