SQL Update a Column From a Select - sql

I want to update 1 column (loadStatus) in the Loads table based on if another column (IBLoad) from a joined table is NULL. The end result when running my statement has 0 rows affected. I'm not sure what's wrong here but maybe my WHERE clause is incorrect?
This is the first time I've tried to update from a select so trying to figure it out :)
UPDATE Loads SET loadStatus = 'SCHEDULED'
FROM (
Select L.OID as [LoadID], T.IBLoad, L.loadStatus
From [Loads] L left join [Transaction] T on L.OID = T.IBLoad
Where T.IBLoad is null and load_type = 1 ) i
WHERE Loads.loadStatus = null

you do not need subquery, And use is null instead of = null
UPDATE L
SET loadStatus = 'SCHEDULED'
From [Loads] L left join [Transaction] T on L.OID = T.IBLoad
Where T.IBLoad is null and load_type = 1
and L.loadStatus is null
or use Loads.loadStatus = '' for empty string

You don't need to update from a select in this case. Here is another way to write the query:
UPDATE l
SET loadStatus = 'SCHEDULED'
FROM Loads l
WHERE l.loadStatus IS NULL AND
l.load_type = 1 AND
NOT EXISTS (SELECT 1 FROM [Transaction] t WHERE l.OID = t.IBLoad);

Related

Trying to update a field conditionally in SQL Stored Procedure

I have a procedure that populates two sets of application information into the same fields. First the fields are filled out with applicable accounts from group "A" and then the same process happens for group "B" accounts.
Most of the group B fields are filled in by a insert/select statement. However, the query to select "account number" is a little more complex and that is in an UPDATE statement. I will paste the code below but I cannot get it to properly update the rows (for group B) with account numbers, despite the fact the query works on its own outside the procedure (essentially, the account numbers do exist).
Any idea why? I tried adding a case statement to single out group B rows (the where clause is hardcoded for group B... e.g. clfcode = 3) but that didn't work. Let me know if you need more information. I haven't much experience with update statements in stored procedures.
update src
set account_key = case when src.clfcode = 3 and src.branch_key = 12 then a.account_key else src.account_key end
from #src_table src
inner join SDFDW_Landing.cu.FICS_ms_Investor_Loan l
on l.loan_id = src.application_number
left join dm.dim_product p
on p.product_key = src.product_key
left join (
Select Distinct t.PARENTACCOUNT, t.USERCHAR1 as loan_id
from SDFDW_Landing.dbo.tracking t
where t.TYPE = 1
and t.ProcessDate = #v_max_last_processed_date
and t.USERCHAR1 is not null
) t on t.loan_id = l.loan_id
left join dm.dim_account a
on t.PARENTACCOUNT = a.account_nkey
WHERE p.bdw_report_category = 'Mortgage'
and l.processdate = #v_max_last_processed_date
The join on a subquery might cause the issue. You could try to replace it with an apply and see if that helps.
update
src
set
account_key =
case
when
src.clfcode = 3
and src.branch_key = 12
then
a.account_key
else
src.account_key
end
from
#src_table src
inner join
SDFDW_Landing.cu.FICS_ms_Investor_Loan l
on l.loan_id = src.application_number
left join
dm.dim_product p
on p.product_key = src.product_key
outer apply (
Select
acc.*
from
dm.dim_account acc
inner join
SDFDW_Landing.dbo.tracking t
on acc.account_nkey = t.parentaccount
where
t.TYPE = 1
and t.ProcessDate = #v_max_last_processed_date
and t.USERCHAR1 is not null
and t.loan_id = l.loan_id
) a
WHERE
p.bdw_report_category = 'Mortgage'
and l.processdate = #v_max_last_processed_date
alternatively since you are already within a stored procedure, I'd populate a temp table with the data from your subquery and simply join on that temp table from your update statement.

Table type of variable returning blank cells after update sql 2008

I have a select query returning two results and what I want is to save them in a table type of variable. This is how I am doing it:
declare #CompletedTotalValues table (CMedian int, CPerc int);
update #CompletedTotalValues set CMedian = t.CMed, CPercentile = t.CPerc
from(
Select CMed = dbo.median(case when cr.Priority = 1 then cr.Days else null end),
CPerc = dbo.Percentile90(case when cr.Priority = 1 then cr.Days else null end)
from A a inner join B b on b.Id = a.Id
where b.StatusId = 3
) t;
Here, when I run the subquery, I see CMed is 25 and CPerc is 43. However, when I execute Select * from #CompletedTotalValues, it is returning both column blank (no value it shows). Where is my mistake? Any advice would be appreciated
Why not just insert the data in the first place?
DECLARE #CompletedTotalValues TABLE (CMedian INT, CPerc INT);
INSERT #CompletedTotalValues (CMedian, CPerc)
SELECT CMed = dbo.median(CASE WHEN cr.Priority = 1 THEN cr.Days END),
CPerc = dbo.Percentile90(CASE WHENn cr.Priority = 1 THEN cr.Days END)
FROM A
INNER JOIN B ON b.Id = a.Id
WHERE b.StatusId = 3;
If I go by the query you have shared, you are trying to update without even inserting any data in the table variable at first place. Is it?

Update statement across multiple fields

I have a table structure (particularly not fond of) where I need to update multiple colums in one row.
Source Table
ID TotalIntake TotalOutput Day
1 1000 500 0
1 1500 1000 1
2 100 200 0
Destination Table (should look like this after update)
ID TotalIntake_0 TotalIntake_1 TotalOutput_0 TotalOutput_1
1 1000 1500 500 1000
2 100 NULL 200 NULL
I tried to use Case when statement, but for some reason it only updates one of each columns and not all the columns across
UPDATE e
Set e.TotalIntake_0 = Case WHEN i.ProcedureDay = 0 Then i.TotalIntake End
,e.TotalIntake_1 = Case WHEN i.ProcedureDay = 1 Then i.TotalIntake End
,e.TotalOutput_0 = Case WHEN i.ProcedureDay = 0 Then i.TotalOutput End
,e.TotalOutput_1 = Case WHEN i.ProcedureDay = 1 Then i.TotalOutput End
FROM DestinationTable e LEFT JOIN SourceTable i ON e.id = i.id
Any ideas greatly appreciated!
Thanks!
Updates on a row are not cumulative. So, only one matching row is used for the update, and you don't know which one. You can do what you want but you need to summarize the rows first and then do the update:
UPDATE e
Set TotalIntake_0 = i.TotalIntake_0,
TotalIntake_1 = TotalIntake_1,
TotalOutput_0 = TotalOutput_0,
TotalOutput_1 = TotalOutput_1
FROM DestinationTable e LEFT JOIN
(select i.id,
TotalIntake_0 = max(Case WHEN i.ProcedureDay = 0 Then i.TotalIntake End),
TotalIntake_1 = max(Case WHEN i.ProcedureDay = 1 Then i.TotalIntake End),
TotalOutput_0 = max(Case WHEN i.ProcedureDay = 0 Then i.TotalOutput End),
TotalOutput_1 = max(Case WHEN i.ProcedureDay = 1 Then i.TotalOutput End)
from SourceTable i
group by i.id
) i
ON e.id = i.id ;
The documentation that describes this is a bit hard to parse:
Use caution when specifying the FROM clause to provide the criteria
for the update operation. The results of an UPDATE statement are
undefined if the statement includes a FROM clause that is not
specified in such a way that only one value is available for each
column occurrence that is updated, that is if the UPDATE statement is
not deterministic. For example, in the UPDATE statement in the
following script, both rows in Table1 meet the qualifications of the
FROM clause in the UPDATE statement; but it is undefined which row
from Table1 is used to update the row in Table2.
I've highlighted the relevant part.
Wouldn't it be simpler to do this in multiple updates?
UPDATE e
SET e.TotalIntake_0 = i.TotalIntake
FROM DestinationTable e
LEFT JOIN SourceTable i ON e.id = i.id
WHERE i.Day = 0
UPDATE e
SET e.TotalIntake_1 = i.TotalIntake
FROM DestinationTable e
LEFT JOIN SourceTable i ON e.id = i.id
WHERE i.Day = 1
Use transactions if necessary.

SQL: Want to alter the conditions on a join depending on values in table

I have a table called Member_Id which has a column in it called Member_ID_Type. The select statement below returns the value of another column, id_value from the same table. The join on the tables in the select statement is on the universal id column. There may be several entries in that table with this same universal id.
I want to adjust the select statement so that it will return the id_values for entries that have member_id_type equal to '7'. However if this is null then I want to return records that have member_id_type equal to '1'
So previously I had a condition on the join (commented out below) but that just returned records that had member_id_type equal to '7' and otherwise returned null.
I think I may have to use a case statement here but I'm not 100% sure how to use it in this scenario
SELECT TOP 1 cm.Contact_Relation_Gid,
mc.Universal_ID,
mi.ID_Value,
cm.First_Name,
cm.Last_Name,
cm.Middle_Name,
cm.Name_Suffix,
cm.Email_Address,
cm.Disability_Type_PKID,
cm.Race_Type_PKID,
cm.Citizenship_Type_PKID,
cm.Marital_Status_Type_PKID,
cm.Actual_SSN,
cm.Birth_Date,
cm.Gender,
mc.Person_Code,
mc.Relationship_Code,
mc.Member_Coverage_PKID,
sc.Subscriber_Coverage_PKID,
FROM Contact_Member cm (NOLOCK)
INNER JOIN Member_Coverage mc (NOLOCK)
ON cm.contact_relation_gid = mc.contact_relation_gid
AND mc.Record_Status = 'A'
INNER JOIN Subscriber_Coverage sc (NOLOCK)
ON mc.Subscriber_Coverage_PKID = sc.Subscriber_Coverage_PKID
AND mc.Record_Status = 'A'
LEFT outer JOIN Member_ID mi ON mi.Universal_ID = cm.Contact_Gid
--AND mi.Member_ID_Type_PKID='7'
WHERE cm.Contact_Relation_Gid = #Contact_Relation_Gid
AND cm.Record_Status = 'A'
Join them both, and use one if the other is not present:
select bt.name
, coalesce(eav1.value, eav2.value) as Value1OrValue2
from BaseTable bt
left join EavTable eav1
on eav1.id = bt.id
and eav1.type = 1
left join EavTable eav2
on eav2.id = bt.id
and eav2.type = 2
This query assumes that there is never more than one record with the same ID and Type.

Update with Subquery

i have a Problem with a query.
I have a huge Table with Zipcodes from Germany called 'Postleitzahlen'.
There is another table with Companies called 'Firmen'
Structure is like this:
Firmen
------
ID
City
State
ZipCode
Postleitzahlen
--------------
ZipCode
State
Now I want, all empty ( '' or NULL ) State-fields of Firmen updated with their correspendants of Postleitzahlen
That's my actual query:
UPDATE
Firmen
SET
Firmen.State = Postleitzahlen.State
FROM
Postleitzahlen
INNER JOIN
Firmen ON Postleitzahlen.ZipCode = Firmen.ZipCode
WHERE
(
Firmen.State = ''
OR Firmen.State IS NULL )
I get a response with xx affected rows, but in fact, there's nothing updated.
Can someone help me?
Thanks in advance.
dennis
That looks like it should work correctly. What I would do is run the below query:
SELECT Firmen.State,Postleitzahlen.State
FROM
Postleitzahlen
INNER JOIN
Firmen ON Postleitzahlen.ZipCode = Firmen.ZipCode
WHERE
(
Firmen.State = ''
OR Firmen.State IS NULL )
See what that gets you. If your get results with values in both columns then you probably have a different issue. However, I am guessing that one of the columns is null or empty since you are updating rows but nothing is changed.
Then there has to be nothing wrong with your query. I think it might be with your update then. Try making the table an alias, like this:
UPDATE
F
SET
F.State = Postleitzahlen.State
FROM
Postleitzahlen
INNER JOIN
Firmen F ON Postleitzahlen.ZipCode = F.ZipCode
WHERE
(
F.State = ''
OR F.State IS NULL )
UPDATE
Firmen f
SET
f.State = (SELECT p.State FROM Postleitzahlen p WHERE p.ZipCode = f.ZipCode)
WHERE
(
f.State = ''
OR f.State IS NULL )