SQL Server Select Statement Trim string - sql-server-2012

I have the below query with PATINDEX where I can find the position of "Kind Regards", however I am trying to remove the string or anything following "Kind Regards".
I do not need the bold text "Good Morning, UPS to support the agent who will be doing standby weekend. Kind Regards Me I"
Can anyone assist, the desired result
"Good Morning, UPS to support the agent who will be doing standby weekend."
when executing a select statement
SELECT
PATINDEX('%Kind%', 'Good Morning, UPS to support the agent who will be doing standby weekend. Kind Regards Me I' )
FROM
CallLog
WHERE
CallID = '01002429'

Use the following:
select Left(ColumnName, IsNull(NullIf(PatIndex('%Kind Regards%',ColumnName),0)-1,Len(ColumnName)))
This will return the string to the left of Kind Regards or the entire string if it doesn't exist.

Related

Where in my query to place the CONVERT to convert DateTime to Date

Just learning SQL and I've searched many options about converting a DateTime into a Date, and I do not want current date. It's a super simple query from this website: https://sqlzoo.net/wiki/Guest_House_Assessment_Easy
SELECT booking_date, nights
FROM booking
WHERE guest_id=1183
But the output is with the timestamp and I just want the date. I've searched so many forums and tried all their suggestions, including this:
SELECT CONVERT(varchar(10), <col>, 101)
So I've done:
SELECT CONVERT(varchar(10), booking_date,101), nights
FROM booking
WHERE guest_id=1183
But I'm getting syntax errors. This is probably so simple and you'll all think me an idiot, but I'd greatly appreciate help. It's driving me nuts.
When I fiddled about at your sqlzoo link I got the error
execute command denied to user 'scott'#'localhost' for routine 'gisq.to_date'`.
When I googled gisq.to_date I got this link https://sqlzoo.net/wiki/Format_a_date_and_time
Which has examples of how this dialect represents dates. See if you can work it out. Something like this:
SELECT date_format(booking_date,'%d/%m/%Y')
FROM booking
You didn't post the error in your question which is a big mistake. When you get an error message, you actually have something to work from.
It is also very important to note that the query above returns a string, not a date. It's only good for display, not for date arithmetic
TBH that seems like a terrible site to learn on as it gives no clues about the dialect. it looks like Oracle but to_date and trunc don't work.
The use of convert() suggests that you think you are uinsg SQL Server. If you only want the date component of a date/time data type, then you can use:
SELECT CONVERT(DATE, booking_date), nights
FROM booking
WHERE guest_id = 1183;
The syntax error suggests that you are not using SQL Server.
CONVERT() is bespoke syntax for SQL Server. Examples of similar functionality in other databases are:
DATE(booking_date)
TRUNC(booking_date)
DATE_TRUNC('day', booking_date)
In addition, what you see also depends on the user-interface.
In your case, the data is being stored as a date with no time component, but the UI is showing the time. For that, you want to convert to a string. That site uses MariaDB -- which is really a flavor of MySQL-- and you would use:
DATE_FORMAT(booking_date, '%Y-%m-%d')

Multiple Replacements with Oracle REGEXP_REPLACE

Ok so an Imperial Agent has gained access to all the Galactic mail servers and has created a mail account for Darth Vadar on each one...
There is a master distribution list maintained in an Oracle Column by the Republic that looks like this:
~To,Chewie,ChewBacca#wookie.net~;~Cc,Han Solo,Millenium#Falcon.com~;~Cc,Luke Skywalker,Luke#IamYourFather.co.uk~
Our Imperial Agent needs help using Oracle REGEXP_REPLACE to replace all the email account names portions with the Darth Vadar account, Vadar#... so the end result would be:
~To,Chewie,Vadar#wookie.net~;~Cc,Han Solo,Vadar#Falcon.com~;~Cc,Luke Skywalker,Vadar#IamYourFather.co.uk~
Can this be done as a single statement?
You would think that using the Dark Force would be easier then this.
Might be too simple for some cases, but for your example this works:
regexp_replace(value, '[[:alnum:]\.]*#', 'Vadar#')
e.g:
select regexp_replace('~To,Chewie,ChewBacca#wookie.net~;~Cc,Han Solo,Millenium#Falcon.com~;~Cc,Luke Skywalker,Luke#IamYourFather.co.uk~',
'[[:alnum:].%_+-]*#', 'Vadar#')
from dual;
~To,Chewie,Vadar#wookie.net~;~Cc,Han Solo,Vadar#Falcon.com~;~Cc,Luke Skywalker,Vadar#IamYourFather.co.uk~
SQL Fiddle with dash and period examples.

SELECT query causes "expression is too complex to evaluate or there is an error"

Initially there were 1000 records to evaluate.Now there are 40000.Please help!
I'm only trying to obtain the week number of a transaction based on transaction date and start date.
SELECT [1_Webtime_By_Date].Badge,Int(((([1_Webtime_By_Date].Date-Forms![Date Form].StartDate)+1.99)/7)+1) AS Week
FROM 1_Webtime_By_Date
GROUP BY [1_Webtime_By_Date].Badge,Int(((([1_Webtime_By_Date].Date-Forms![Date Form].StartDate)+1.99)/7)+1);
This is a known issue with the compiler used by Access. Limits of 64K segments were lifted after Access 97 but the amount of data you are quering is simply too much for Access. There are a few tips given on the following page that may help but it seems to me that you need to use a proper database system such as MS SQL. There is a free version available (SQL Express) if it's cost that is the problem.
ACC: "Out of Memory" or "Query Too Complex" with Query/Report
SQL Server Express Download page
You may find that using SQL Server as a database and Access as a front end may help your problems if you are tied to using Access for end users.
The best tip given is to use aliasing to shorten the length of your query and to try to remove nested queries:
Access SQL: FROM clause
My first inclination is to add some white space before and after both the minus signs.
My next test would to make the form field into a DATE type, and use something like
DATEPART(ww,[1_Webtime_By_Date].Date - Forms![Date Form].StartDate ) AS WK

SQL - User input in query

I have this. "Detail all films shown by the club between any two given dates, inputted by the user. For example a club member must be able to input a start date and an end date for the parameters for the query"
Now, how would I go about doing the user input? Only way I can think of would to be using php or something with a html form getting the values and then submitting them as variables in the query. However, that's not what is needed. So, how is this done so the query would ask for values? Or can't you?
My query so far looks like so.
SELECT film.title, film.desc, show.sdate, show.fdate
FROM film
INNER JOIN show
ON film.ID=show.filmID
WHERE sdate = '&userstart' AND fdate = '&userend'
How do I go about with the user input? Also, is the query correct? I have no way of testing, I only have a design not an implementation.
Thanks a lot
Edit: Using Windows system, MS SQL Server.
Here's the code for a stored procedure:
CREATE PROCEDURE SomeName(#UserStart DATETIME, #UserEnd DATETIME)
AS BEGIN
SELECT somestuff
FROM sometable
WHERE somedate BETWEEN #UserStart AND #UserEnd
END
#Kyle93 -
Looking at your WHERE Clause:
WHERE sdate = '&userstart' AND fdate = '&userend'
This will only get you Films that had a sdate(Start Date?) equal to the date value entered.
You might want to use Greater than, Less Than operators....
Such as:
WHERE sdate <= '&userend' AND fdate >= '&userstart'
(Note comparing sdate to UserEnd Date to make sure Film Showing started EARLIER than the UserEnd Date...etc)
This way - when a show starts OR ends within the date range - it will be selected.
Are you familiar at all with LINQ? It's a way to make db calls from c#.
-- I would handle this with HTML as you thought, and use Javascript/Ajax to reference c# code that uses LINQ for db calls. Might be a bit complicated however, if you're not familiar with much of that. I can recommend good tutorials if interested tho.

What's the best approach to embed RegEx in Oracle or SQL Server 2005 SQL?

This is a 3 part question regarding embedded RegEx into SQL statements.
How do you embed a RegEx expression into an Oracle PL/SQL
select statement that will parse out
the “DELINQUENT” string in the text
string shown below?
What is the performance impact if used within a
mission critical business
transaction?
Since embedding regex
into SQL was introduced in Oracle
10g and SQL Server 2005, is it
considered a recommended practice?
Dear Larry :
Thank you for using ABC's alert service.
ABC has detected a change in the status of one of your products in the state of KS. Please review the
information below to determine if this status change was intended.
ENTITY NAME: Oracle Systems, LLC
PREVIOUS STATUS: --
CURRENT STATUS: DELINQUENT
As a reminder, you may contact your the ABC Team for assistance in correcting any delinquencies or, if needed, reinstating
the service. Alternatively, if the system does not intend to continue to engage this state, please notify ABC
so that we can discontinue our services.
Kind regards,
Service Team 1
ABC
--PLEASE DO NOT REPLY TO THIS EMAIL. IT IS NOT A MONITORED EMAIL ACCOUNT.--
Notice: ABC Corporation cannot independently verify the timeliness, accuracy, or completeness of the public information
maintained by the responsible government agency or other sources of data upon which these alerts are based.
Why would you need regular expressions here?
INSTR and SUBSTR will do the job perfectly.
But if you convinced you need Regex'es you can use:
REGEXP_INSTR
REGEXP_REPLACE
REGEXP_SUBSTR
(only available in Oracle 10g and up)
SELECT emp_id, text
FROM employee_comment
WHERE REGEXP_LIKE(text,'...-....');
If I recall correctly, it is possible to write a UDF in c#/vb for SQL Server.
Here's a link, though possibly not the best: http://www.novicksoftware.com/coding-in-sql/Vol3/cis-v3-N13-dot-net-clr-in-sql-server.htm
Why not just use INSTR (for Oracle) or CHARINDEX (for SQL Server) combined with SUBSTRING? Seems a bit more straightforward (and portable, since it's supported in older versions).
http://www.techonthenet.com/oracle/functions/instr.php and http://www.adp-gmbh.ch/ora/sql/substr.html
http://www.databasejournal.com/features/mssql/article.php/3071531 and http://msdn.microsoft.com/en-us/library/ms187748.aspx
INSTR and CHARINDEX are great alternative approaches but I'd like to explore the benefits of embedding Regex.
In MS SQL you can use LIKE which has some "pattern matching" in it. I would guess Oracle has something similar. Its not Regex, but has some of the matching capabilities. (Note: its not particularly fast).. Fulltext searching could also be an option (again MS SQL) (probably a much faster way in the context of a good sized database)