SQL Server - Execute Dynamic SQL for Each Row in Recordset - sql

I have a population of students who are registered to take courses for the Fall semester, with each course having it's own particular prerequisite requirements.
LastName FirstName Course Prerequisite(s)
Smith John ET212 (NS292 And NS262 And NS271) OR (( NS272 OR CR313 ) AND CS134)
Smith John ET452 HC111
Apon Jim EG442 EG243
Apon Jim EG497 EG382 And EG431
Jones Greg MS160 MS150
Jones Greg NV222 NV101 Or NV212
Serandon Susan EG261 EG101
I created a function that finds the the prerequisites for a course and builds a predicate string in proper SQL (or at least close to it - I haven't been able to test), with consideration for the AND / OR combinations of different prerequisite courses:
NOT EXISTS (SELECT * FROM TRANSCRIPT WHERE ID = 'P000021210' AND COURSE = 'ET211') And NOT EXISTS (SELECT * FROM TRANSCRIPT WHERE ID = 'P000021210' AND COURSE = 'ES251')
I was hoping to use this function to build a SQL statement for each row in my recordset (every class that every student is registered to take), execute that statement, and then return a bit; yes, they meet the prerequisite requirements to take the course, or no, they don't. BUT, apparently you can't use sp_executesql or EXECUTE() within a function.
So the root of my question is, since it does not appear possible to execute a dynamic SQL statement unique to each row in a recordset, how else could I accomplish this?

Related

Exact String match using oracle CONTAINS for multiple values

I need to get exact name string match from multiple values using Contains function.
I used below query to get data which matches exactly JOHN SMITH OR MIKE DAVID but query is fetching all data which has JOHN SMITH, JOHN, SMITH, MIKE, DAVID, MIKE DAVID, JOHN..SMITH, JOHN/SMITH,....
where contains(names,'{JOHN SMITH} OR {MIKE DAVID}')>0
Note - I don't want to use multiple like in OR conditions.We need to pass around 200 to 300 values (names) to do match pattern.
Can anyone let me know how to get exact match from multiple values using CONTAINS?
Thanks
Anand
I don't use Oracle but i liked this question and i will try to answer it based on what i read on Oracle's documentation, regarding CONTAINS.
so i am currently reading about Stored Query Expression (SQE),
Stored Query Expression (SQE)
Use the SQE operator to call a stored query expression created with
the CTX_QUERY.STORE_SQE procedure.
Stored query expressions can be used for creating predefined bins for
organizing and categorizing documents or to perform iterative queries,
in which an initial query is refined using one or more additional
queries.
So perhaps you could pass all the names you want to query in such a way. For example:
begin
ctx_query.store_sqe('mynames', 'JOHN SMITH OR MIKE DAVID OR GEORGE HARRIS OR JOHN DOE');
end;
And then call it:
SELECT SCORE(1), nameid FROM mytable
WHERE CONTAINS(names, 'sqe(mynames)', 1)> 0
ORDER BY SCORE(1);
Hope this was helpful.

MS-Access, update a value based on what the client wants using forms

I have to create a form where you select your studentID and what class you want to change to. For example:
Student Table
StudentID Student Name Class
1 John Smith Biology
2 Elan Carter Math
3 Bob White Literature
In my form I ask for the student number and the associated information pulls up (I have this working correctly).
Form
What is your StudentID? 1
Student Name: John Smith
Class: Biology
Now I want another option to be able to change class. Let's say for example, change studentID 1's (John Smith) current class from Biology to Math
Updated
What class do you want to transfer to? Math
Student Name: John Smith
Class: Biology
I considered the append and delete version but currently working on using the update query:
UPDATE Student
SET Student.[Student Name] = ""
WHERE
I'm confused because I don't understand how I can complete the query while taking into consideration of the multiple options. Thank you!
**PS-- I'm using queries to create the data in the form in MS ACCESS if there is any confusion.
**PSS---Tried this code but no success (Syntax error at JOIN operation)
UPDATE Student.[Student Name]
INNER JOIN Student ON Class.[Student Name] = Student.[Student Name]
SET Student.[Student Name] = Student.[Student Name]
If you're wondering about the Class table it's just:
Class
Biology
Math
Literature

Updating a database column based on its similarity to another database column

I have a database table (Customers) with the following columns:
ID
FIRST_NAME
MIDDLE_INIT
LAST_NAME
FULL_NAME
I also have a database table (ENG) with the following columns:
ID
ENG_NAME
I want to replace all of the ENG.ENG_NAME entries with a FULL_NAME entry from the CUSTOMERS table
Here is the problem.
The ENG_NAME was hand-jammed through a web form and, so, has no consistency. For instance, one row might contain "Robin Hood". Another "Hood, Robin L". An another "Robin L Hood".
I want to search the entries in the CUSTOMERS table, find a close match, then replace the ENG.ENG_NAME with the CUSTOMERS.FULL_NAME.
Example:
ENG table CUSTOMERS table
ID ENG_NAME ID FULL_NAME FIRST_NAME MIDDLE_INIT LAST_NAME
================ ==================================================================
1 Hood,Robin 1 Robin L Hood Robin L Hood
2 Rob Hood 2 Maid M Marion Maid M Marion
3 Marion M 3 Friar F Tuck Friar F Tuck
4 Rob Garza 4 Robert A Garza Robert A Garza
Based on the data above, I would want ENG_NAME columns to be replaced like this:
ENG table
ID ENG_NAME
====================
1 Robin L Hood
2 Robin L Hood
3 Maid M Marion
4 Robert A Garza
Any thoughts on how to do this?
Thanks
This is not going to be a simple task, I would start at finding a good C# (or any .NET) algorithm that detects similar strings portions.
Then look at Compiling C# Code into SQL Stored Procedures and Invoke that code using SQL Server. This CLR Code can then write the results to a table for you to analyze and do whatever you want with it.
For More: CLR SQL Server User-Defined Function
I would do it in .NET using Levenshtein distance.
Start at 1 and you are going to have some ties and you need to decide
Then move to 2,3,4...
You could do in a CLR but how are you going to deal with ties? And you are going to have ties. How are you going to decide when it is not a match at all?
And I would put it in new column so you have a history of original data
Or a FK reference to customers table

SQL style query in MATLAB

Can I do SQL-style query on an in-memory dataset (or cellarray, or structure, etc) in MATLAB?
Why I ask is, sometimes, I don't want to talk to the database for 1000 times when I want to do different operations on each of the 1000 rows of data. Instead, I'd rather read all 1000 from the database and operate on them in MATLAB.
For example, I have read the following out of from the database:
age first_name last_name income
30 Mike Smith 45
17 David Oxgon 17
22 Osama Lumbermaster 3
Now I want to find out the full names of the people that are under the age of 25. I know how to do it, but is there any syntax as clean and intuitive as SQL like this?
SELECT first_name + ' ' + last_name AS name FROM people WHERE age < income
In the docs page Access Data in a Table (see the example Index Using a Logical Expression) it shows that your examples could be achieved as follows:
MyTable({'first_name','last_name'}, MyTable.age < MyTable.income)
These docs don't specifically explain how to merge the name and surname into one variable but I'm sure it's easy. Give it a try and let us know if you get it.

Getting distinct rows based on a certain field from a database in Django

I need to construct a query in Django, and I'm wondering if this is somehow possible (it may be really obvious but I'm missing it...).
I have a normal query Model.objects.filter(x=True)[:5] which can return results like this:
FirstName LastName Country
Bob Jones UK
Bill Thompson UK
David Smith USA
I need to only grab rows which are distinct based on the Country field, something like Model.objects.filter(x=True).distinct('Country')[:5] would be ideal but that's not possible with Django.
The rows I want the query to grab ultimately are:
FirstName LastName Country
Bob Jones UK
David Smith USA
I also need the query to use the same ordering as set in the model's Meta class (ie. I can't override the ordering in any way).
How would I go about doing this?
Thanks a lot.
I haven't tested this, but it seems to me a dict should do the job, although ordering could be off then:
d = {}
for x in Model.objects.all():
d[x.country] = x
records_with_distinct_countries = d.values()
countries = [f.country in Model.objects.all()]
for c in countries:
try:
print Model.objects.filter(country=c)
except Model.DoesNotExist:
pass
I think that #skrobul is on the right track, but a little bit off.
I don't think you'll be able to do this with a single query, because the distinct() method adds the SELECT DISTINCT modifier to the query, which acts on the entire row. You'll likely have to create a list of countries and then return limited QuerySets based on iterating that list.
Something like this:
maxrows = 5
countries = set([x.country for x in Model.objects.all()])
rows = []
count = 0
for c in countries:
if count >= maxrows:
break
try:
rows.append(Model.objects.filter(country=c)[0])
except Model.DoesNotExist:
pass
count += 1
This is a very generic example, but it gives the intended result.
Can you post the raw SQL that returns what you want from the source database? I have a hunch that the actual problem here is the query/data structure...