How to call function in update statement - tsql

I can get the first, middle, last name for a function passing a string. How do I pass the element in the query to the function for an update statement.
--test update logic, and name parsing
USE PCUnitTest
UPDATE p
SET --Need FIRST_NAME, MIDDLE_NAME, LAST_NAME
p.FIRST_NAME = SELECT forename FROM (SELECT * FROM dbo.NameParser(c.CONTACT)) AS FirstName, --shows multipart identifier could not be bound
p.FIRST_NAME = SELECT forename FROM (SELECT * FROM dbo.NameParser('Andy D Where')) AS FirstName, --returns Andy
p.MIDDLE_NAME = SELECT middle_name FROM (SELECT * FROM dbo.NameParser('Andy D Where')) AS MiddleName, --returns D
p.LAST_NAME = SELECT surname FROM (SELECT * FROM dbo.NameParser('Andy D Where')) AS LastName --returns Where
FROM GMUnitTest.dbo.CONTACT1 c
JOIN PCUnitTest.dbo.PEOPLE p
ON p.PEOPLE_ID = c.KEY4
WHERE c.Key1 = '76'; --Test with a current string
GO

I think you mean to do something similar to this:
USE PCUnitTest
GO
UPDATE P
SET
P.First_Name = T.ForeName
,P.Middle_Name = T.Middle_Name
,P.Last_name = T.Surname
FROM GMUnitTest.dbo.Contact1 C
INNER JOIN PCUnitTest.dbo.People P
ON P.People_ID = C.Key4
CROSS APPLY dbo.NameParser(C.Contact) T
WHERE C.Key1 = '76'
;
I don't know what you're using to parse the names, but I can see that it always returns the first name, middle name, and last name. You might want to consider adding an extra input parameter to your function so that you can specifically request the first, middle, or last name by entering a numerical (or other) parameter.
In the query up above, each name would return duplicate results, so you would probably end up running an UPDATE against the same value a few times, each time with the same value.
By adding another parameter to your function, you could use CROSS APPLY several times (or OUTER APPLY if there's a chance that one or more monikers are missing) in order to update more efficiently, as such:
USE PCUnitTest
GO
UPDATE P
SET
P.First_Name = FirstName.ForeName
,P.Middle_Name = MiddleName.Middle_Name
,P.Last_name = LastName.Surname
FROM GMUnitTest.dbo.Contact1 C
INNER JOIN PCUnitTest.dbo.People P
ON P.People_ID = C.Key4
CROSS APPLY dbo.NameParser(C.Contact,1) FirstName
CROSS APPLY dbo.NameParser(C.Contact,2) MiddleName
CROSS APPLY dbo.NameParser(C.Contact,3) LastName
WHERE C.Key1 = '76'
;

Related

Postgres get rows which hasnt match in other table

I need your help. I need an advanced Query to my database. Im showing part of my database following:
Place (id, name, address)
Local (id, place_id, name)
PlaceReservation(id, local_id, date)
Media_Place (id, place_id, type)
Now I need a query, which gets all places with logo, which have AT LEAST ONE local which hasn't been reserved on a specific day e.g: 2015-07-01.
Help me please, because I haven't an idea how to do it. I thought about an outer join but I don't know how use it.
I was trying by:
$query = 'SELECT DISTINC *,
(SELECT sum(po.rating)/count(po.id)
FROM "Place_Opinion" po
WHERE po.place_id = p.id AND po.deleted = false) AS rating,
mp.path as logo_path
FROM "Place" p
INNER JOIN "Media_Place" mp ON mp.place_id = p.id
JOIN Local ON Local.place_id = Place.id
LEFT JOIN (
SELECT id AS rr, local_id
FROM PlaceReservation
WHERE date_start = \'2015-07-01\') Reserved ON Reserved.local_id = Local.id
WHERE mp.type = ' . Model_Row_MediaPlace::LOGO_TYPE . '
AND mp.deleted = false
AND p.deleted = false
AND rr IS NULL';
Looking for things that do not exist in a database is usually very inefficient. But you can change the logic around by finding places that do have a booking for the specified date, then LEFT JOIN that to all places with a logo and filter out the records with a reservation:
SELECT DISTINCT p.*, po.rating, mp.path as logo_path
FROM "Place" p
JOIN "Media_Place" mp ON mp.place_id = p.id AND mp.deleted = false AND mp.type = ?
JOIN Local ON Local.place_id = p.id
LEFT JOIN (
SELECT id AS rr, local_id
FROM PlaceReservation
WHERE date_start = '2015-07-01') reserved ON reserved.local_id = Local.id
LEFT JOIN (
SELECT place_id, avg(rating) AS rating
FROM "Place_Opinion"
WHERE deleted = false
GROUP BY place_id) po ON po.place_id = p.id
WHERE p.deleted = false
AND reserved.rr IS NULL;
The average rating per places is calculated in a separate sub-query. The error you had was because you referenced the "Place" table (p.id) before it was defined. For simple columns you can do that, but for sub-queries you can't.

TSQL efficiency - INNER JOIN replaced by EXISTS

Can the following be rewritten to be more efficient?
I would use EXISTS if I didn't need fields from country but I do need those fields, and am not sure how to write this to make it more efficient.
SELECT distinct
p.ProvinceID,
p.Abbv as RegionCode,
p.name as RegionName,
cn.Code as CountryCode,
cn.Name as CountryName
FROM dbo.provinces AS p
INNER JOIN dbo.Countries AS cn ON p.CountryID = cn.CountryID
INNER JOIN dbo.Cities c on c.ProvinceID = p.ProvinceID
INNER JOIN dbo.Listings AS l ON l.CityID = c.CityID
WHERE l.IsActive = 1 AND l.IsApproved = 1
There are two things to note:
You're joining to dbo.Listings which results in many records, so you need to use DISTINCT (usually an expensive operator)
For any tables with columns not in the select you can move into an EXISTS (but the query planner effectively does this for you anyway)
So try this:
SELECT
p.ProvinceID,
p.Abbv as RegionCode,
p.name as RegionName,
cn.Code as CountryCode,
cn.Name as CountryName
FROM dbo.provinces AS p
INNER JOIN
dbo.Countries AS cn
ON p.CountryID = cn.CountryID
WHERE EXISTS (SELECT 1 FROM
dbo.Listings l
INNER JOIN dbo.Cities c
on l.CityID = c.CityID
WHERE c.ProvinceID = p.ProvinceID
AND l.IsActive = 1 AND l.IsApproved = 1
)
Check the query plans before and after - the query planner might be smart enough to do this anyway, but you have removed your distinct
The following will often perform even better by providing the optimizer more useful information:
SELECT
p.ProvinceID,
p.Abbv as RegionCode,
p.name as RegionName,
cn.Code as CountryCode,
cn.Name as CountryName
FROM dbo.provinces AS p
INNER JOIN
dbo.Countries AS cn
ON p.CountryID = cn.CountryID
INNER JOIN (
SELECT
p.ProvinceID
FROM
dbo.Listings l
INNER JOIN dbo.Cities c
on l.CityID = c.CityID
WHERE l.IsActive = 1 AND l.IsApproved = 1
GROUP BY
p.ProvinceID
) list
on list.ProvinceID = p.ProvinceID

Deleting from an aliased join construct

I want to delete from a join construct, that I have to supply an alias ("mapped") for, since I also have to use an EXISTS clause on the join in the end. So the whole thing looks something like that:
DELETE a
FROM (TableA a INNER JOIN
(SELECT * FROM TableX x INNER JOIN TableY y ON x.id = y.id) map
ON a.key = map.key) mapped
WHERE EXISTS
(SELECT *
FROM LookUp l
WHERE l.key1 = mapped.TableAKey
AND l.key2 = mapped.TableXKey
AND l.key3 = mapped.TableYKey)
The problem seems to be with the parenthesis, because I get an error:
Incorrect syntax near 'mapped'.
Any help would be appreciated.
Just rewrite it so you're deleting from an explicit table and handle all of your conditions in the where clause something like this.
DELETE TableA
WHERE
EXISTS (
SELECT *
FROM
TableX x
INNER JOIN TableY y ON x.id = y.id
WHERE
x.key = TableA.key and
EXISTS (
SELECT *
FROM LookUp l
WHERE l.key1 = TableA.TableAKey
AND l.key2 = x.TableXKey
AND l.key3 = y.TableYKey
)
)
Also note it may be helpful to replace DELETE TableA with SELECT * FROM TableA while you're working on the where clause to see exactly what records are going to be deleted.
I believe the DELETE statement needs to reference an alias used in your FROM clause. Since your alias is 'mapped', try changing the DELETE as follows:
DELETE mapped
FROM (TableA a INNER JOIN
(SELECT * FROM TableX x INNER JOIN TableY y ON x.id = y.id) map
ON a.key = map.key) mapped
WHERE EXISTS
(SELECT *
FROM LookUp l
WHERE l.key1 = mapped.TableAKey
AND l.key2 = mapped.TableXKey
AND l.key3 = mapped.TableYKey)

T-SQL Query, combine columns from multiple rows into single column

I have seeen some examples of what I am trying to do using COALESCE and FOR XML (seems like the better solution). I just can't quite get the syntax right.
Here is what I have (I will shorten the fields to only the key ones):
Table Fields
------ -------------------------------
Requisition ID, Number
IssuedPO ID, Number
Job ID, Number
Job_Activity ID, JobID (fkey)
RequisitionItems ID, RequisitionID(fkey), IssuedPOID(fkey), Job_ActivityID (fkey)
I need a query that will list ONE Requisition per line with its associated Jobs and IssuedPOs. (The requisition number start with "R-" and the Job Number start with "J-").
Example:
R-123 | "PO1; PO2; PO3" | "J-12345; J-6780"
Sure thing Adam!
Here is a query that returns multiple rows. I have to use outer joins, since not all Requisitions have RequisitionItems that are assigned to Jobs and/or IssuedPOs (in that case their fkey IDs would just be null of course).
SELECT DISTINCT Requisition.Number, IssuedPO.Number, Job.Number
FROM Requisition
INNER JOIN RequisitionItem on RequisitionItem.RequisitionID = Requisition.ID
LEFT OUTER JOIN Job_Activity on RequisitionItem.JobActivityID = Job_Activity.ID
LEFT OUTER JOIN Job on Job_Activity.JobID = Job.ID
LEFT OUTER JOIN IssuedPO on RequisitionItem.IssuedPOID = IssuedPO.ID
Here's one way to do it using subqueries:
select 'R-' + cast(r.number as varchar(32)) as RequisitionNumber
, (
select 'PO' + CAST(ip.number as varchar(32)) + ';'
from IssuedPO ip
join RequisitionItems ri
on ip.id = ri.IssuedPOID
where ri.RequisitionID = r.id
for xml path('')
) as POList
, (
select 'J-' + CAST(j.number as varchar(32)) + ';'
from Job j
join Job_Activity ja
on j.id = ja.JobID
join RequisitionItems ri
on ri.Job_ActivityID = ja.id
where ri.RequisitionID = r.id
for xml path('')
) as JobList
from Requisition r

T-SQL Problem converting a Cursor into a SET based operation

Basically I have this cursor that was not written by me but is taking some time to process and I was wanting to try and improve it by getting rid of the cursor all together.
Here is the code:
DECLARE #class_id int, #title_code varchar(30)
DECLARE title_class CURSOR FOR
SELECT DISTINCT title_code FROM tmp_business_class_titles (NOLOCK)
OPEN title_class
FETCH title_class INTO #title_code
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT TOP 1 #class_id = bc1.categoryid
FROM tmp_business_class_titles bct,
dbo.Categories bc1 (nolock)
join dbo.Categories bc2 (nolock) on bc2.categoryid = bc1.highercategoryid
join dbo.Categories bc3 (nolock) on bc3.categoryid = bc2.highercategoryid
WHERE bc1.categoryid = bct.class_id
AND title_code = #title_code
ORDER BY Default_Flag DESC
UPDATE products
SET subcategoryid = #class_id
WHERE ccode = #title_code
AND spdisplaytype = 'Table'
UPDATE products
SET subcategoryid = #class_id
WHERE highercatalogid IN (
SELECT catalogid FROM products (nolock)
WHERE ccode = #title_code AND spdisplaytype = 'Table')
FETCH title_class INTO #title_code
END
CLOSE title_class
DEALLOCATE title_class
The table tmp_business_class_titles looks like this:
class_id,title_code,Default_flag
7,101WGA,0
7,10315,0
29,8600,0
The default flag can always be 0 but if it is 1 then the logic should automatically pick the default class_id for that title_id.
So the current logic loops through the above table in a cursor and then selects the top 1 class id for each title, ordered by the the default flag (so the class_id with a default_flag of 1 should always be returned first.) and applies the default class_id to the products table.
This code takes around 1:20 to run and I am trying to convert this into one or 2 update statements but I have exhausted my brain in doing so.
Any TSQL Guru's have any ideas if this is possible or should I re-evaluate the entire logic on how the default flag works?
cheers for any help.
I don't have quite enough information to work with, so the following query is likely to fail. I particularly need more information on the products table to make this work, but assuming that you have SQL Server 2005 or higher, this might be enough to get you started in the right direction. It utilizes common table expressions along with the RANK function. I highly recommend learning about them, and in all likelihood, it will greatly improve the efficiency of the query.
;WITH cteTitle As (
SELECT
sequence = RANK() OVER (PARTITION BY bct.title_code ORDER BY Default_Flag desc)
,bct.title_code
,bc1.categoryid
FROM
tmp_business_class_titles bct
join Categories bc1 ON bc1.categoryid = bct.class_id
join Categories bc2 ON bc2.categoryid = bc1.highercategoryid
join Categories bc3 ON bc3.categoryid = bc2.highercategoryid
)
UPDATE
prod
SET
subcategoryid = ISNULL(t.categoryid,t2.categoryid)
FROM
products prod
LEFT join products subprod ON subprod.catalogid = prod.highercatalogid
LEFT join cteTitle t ON prod.ccode = t.title_code AND t.sequence = 1 AND prod.spdisplaytype = 'Table'
LEFT join cteTitle t2 ON subprod.ccode = t2.title_code And t2.sequence = 1 AND subprod.spdisplaytype = 'Table'
WHERE
t2.categoryid IS NOT NULL