Update data in temporary table with new records found with joins on other table - sql

I have data in a temporary table and I need to update this with the new data found with other tables using joins. How can I change the second select to an update statement?
Can you please suggest how to do this?
Thank you
SELECT
sc.str_psn, sc.str_esn, sc.id_smartcard, sc.id_customer, st.str_statusdesc,
pax.str_title
INTO #temp
FROM Smartrack.dbo.Smartcard sc
INNER JOIN Smartrack.dbo.Customer pax on sc.id_customer = pax.id_customer
INNER JOIN SmarTrack.dbo.StatusType st ON sc.int1_cardstatus = st.int1_statustype
SELECT
t.str_psn , t.str_esn, t.id_smartcard, t.id_customer, t.str_statusdesc,
t.str_title, subpax.datAdded, tok.str_token_desc, subpax.ultTokenType
FROM #temp t
INNER JOIN (
SELECT p.id_Customer, u.id_TravelToken, u.ultTokenType, u.datAdded, u.ultTokenExpiry
FROM SmarTrack.dbo.Customer p
INNER JOIN SmarTrack.dbo.Smartcard s ON p.id_customer = s.id_customer
INNER JOIN SmartrackInterface.dbo.vwUltimateCardDetails u ON s.id_smartcard = u.id_smartcard
WHERE s.id_replacement_smartcard IS NULL
) subpax ON t.id_customer = subpax.id_CUstomer
INNER JOIN SmarTrack.dbo.TravelToken tt ON subpax.id_TravelToken = tt.id_traveltoken
INNER JOIN SmarTrack.dbo.TokenType tok on subpax.ultTokenType = tok.int2_tokentype

Your question is similar to this: Update records in table from CTE
Your can try the following method
with cte as(
SELECT
t.str_psn , t.str_esn, t.id_smartcard, t.id_customer, t.str_statusdesc,
t.str_title, subpax.datAdded, tok.str_token_desc, subpax.ultTokenType
FROM #temp t
INNER JOIN (
SELECT p.id_Customer, u.id_TravelToken, u.ultTokenType, u.datAdded, u.ultTokenExpiry
FROM SmarTrack.dbo.Customer p
INNER JOIN SmarTrack.dbo.Smartcard s ON p.id_customer = s.id_customer
INNER JOIN SmartrackInterface.dbo.vwUltimateCardDetails u ON s.id_smartcard = u.id_smartcard
WHERE s.id_replacement_smartcard IS NULL
) subpax ON t.id_customer = subpax.id_CUstomer
INNER JOIN SmarTrack.dbo.TravelToken tt ON subpax.id_TravelToken = tt.id_traveltoken
INNER JOIN SmarTrack.dbo.TokenType tok on subpax.ultTokenType = tok.int2_tokentype
)
Update #temp
Set #temp.id_customer in (Select distinct id_customer From cte)

Related

Where Clause Using Conditional Statement

i have query below
SELECT #RoleUser = MR.Code FROM MasterRole MR INNER JOIN MasterUsersRole MUR ON MR.Id = MUR.RoleId
INNER JOIN MasterUsers MU ON Mu.UserCode = MUR.UserCode
WHERE MU.UserCode = #UserLoginID
select 1 Num
, MyHistory.ID
, MyHistory.RequestNumber
, MyHistory.FlowID
, MyHistory.FlowProcessStatusID
from
(
select *
from Requests R
inner join
(
--DECLARE #UserLoginID nvarchar(200) = 'dum.testing.3'
select distinct
RequestID
from dbo.RequestTrackingHistory RTH
where IIF(#UserLoginID = 'admin', #UserLoginID, RTH.CreatedBy) = #UserLoginID
OR ( CreatedBy IN
SELECT Mu.UserCode from MasterUsers MU
INNER JOIN MasterUsersRole MUR ON MU.UserCode = MUR.UserCode
INNER JOIN MasterRole MR ON MUR.RoleId = MR.Id
WHERE MR.Code = #RoleUser
)
)
) RT on R.ID = RT.RequestID
) as MyHistory
inner join MasterFlow F on MyHistory.FlowID = F.ID
inner join
(
select FP.ID
, FP.Name
, FP.AssignType
, FP.AssignTo
, FP.IsStart
, case FP.AssignType
when 'GROUP' then
G.Name
end as 'AssignToName'
from MasterFlowProcess FP
left join dbo.MasterRole G on FP.AssignTo = G.ID and FP.AssignType = 'GROUP'
) FP on MyHistory.FlowProcessID = FP.ID
inner join MasterFlowProcessStatus FPS on MyHistory.FlowProcessStatusID = FPS.ID
left join MasterFlowProcessStatusNext FPSN on FPS.ID = FPSN.ProcessStatusFlowID
left join MasterFlowProcess FPN on FPSN.NextProcessFlowID = FPN.ID
left JOIN MasterRole MR ON MR.Id = FPN.AssignTo
left join MasterUsersRole MUR on MR.Id = MUR.RoleId
left join MasterUsers MURO on MUR.UserCode = MURO.UserCode
inner join MasterUsers UC on MyHistory.CreatedBy = UC.UserCode
left join MasterUsers UU on MyHistory.UpdatedBy = UU.UserCode
LEFT JOIN RequestMT RMT ON MyHistory.ID = RMT.RequestID
LEFT JOIN RequestGT RGT ON MyHistory.ID = RGT.RequestID
left join (SELECT sum(QtyCU) countQty , RequestId from dbo.RequestGTDetail where IsActive = 1 group by RequestId) RGTD on RGTD.RequestId = RGT.RequestId
left join (SELECT sum(QtyPCS) countQty , RequestId from dbo.RequestMTDetail where IsActive = 1 group by RequestId) RMTD on RMTD.RequestId = RMT.RequestId
left join (SELECT COUNT(IIF(returnable = 0, returnable, null)) countReturnable , RequestId from dbo.RequestMTDetail group by RequestId) RMTR on RMTR.RequestId = RMT.RequestId
left JOIN dbo.MasterDistributor md ON md.Code = RGT.CustId or md.Code = RMT.CustId
left JOIN dbo.MasterUsersDistributor MUD ON MUD.UserCode = MURO.UserCode AND md.Code = MUD.DistributorCode
LEFT JOIN dbo.MasterReason MRMT ON RMT.ReasonId = MRMT.Id
LEFT JOIN dbo.MasterReason MRGT ON RGT.ReasonId = MRGT.Id
LEFT JOIN dbo.MasterDistributorGroup MDG ON MDG.Id = MD.GroupId
OUTER APPLY dbo.FnGetHistoryApproveDate(MyHistory.Id) AS x
where REPLACE(FPS.Name, '#Requestor', uc.Name) <> 'DRAFT'
AND MUD.DistributorCode IN (SELECT DistributorCode FROM dbo.MasterUsersDistributor WHERE UserCode = #UserLoginID)
i want to add some logic in where clause
this line
==> AND MUD.DistributorCode IN (SELECT DistributorCode FROM dbo.MasterUsersDistributor WHERE UserCode = #UserLoginID)
it depend on the #RoleUser variable, if #RoleUser IN ('A','B') then where clause above is executed, but if #RoleUser Not IN ('A','B') where clause not executed
i,m trying this where clause
AND IIF(#RoleUser IN ('A','B'), MUD.DistributorCode, #RoleUser) IN (SELECT DistributorCode FROM dbo.MasterUsersDistributor WHERE UserCode = IIF(#RoleUser IN ('A','B'), #UserLoginID, NULL))
it didn't work, only executed if #RoleUser IS ('A','B') other than that it return 0 record
any help or advice is really appreciated
thank you
The cleanest way I'm implemented these kind of crazy rules is a
holderTable
and a countVariable against the holder table.
I'll give a generic examples.
This is a "approach" and "philosophy", not a specific answer....with complex WHERE clauses.
DECLARE #customerCountryCount int
DECLARE #customerCountry TABLE ( CountryName varchar(15) )
if ( "the moon is blue on tuesday" ) /* << whatever rules you have */
BEGIN
INSERT INTO #customerCountry SELECT "Honduras" UNION ALL SELECT "Malaysia"
END
if ( "favorite color = green" ) /* << whatever rules you have */
BEGIN
INSERT INTO #customerCountry SELECT "Greenland" UNION ALL SELECT "Peru"
END
SELECT #customerCountryCount = COUNT(*) FROM #customerCountry
Select * from dbo.Customers c
WHERE
(#customerCountryCount = 0)
OR
( exists (select null from #customerCountry innerVariableTable where UPPER(innerVariableTable.CountryName) = UPPER(c.Country) ))
)
This way, instead of putting all the "twisted logic" in an overly complex WHERE statement..... you have "separation of concerns"...
Your inserts into #customerCountry are separated from your use of #customerCountry.
And you have the #customerCountryCount "trick" to distinguish when nothing was used.
You can add a #customerCountryNotExists table as well, and code it to where not exists.
As a side note, you may want to try using a #temp table (instead of a #variabletable (#customerCountry above)... and performance test these 2 options.
There is no "single answer". You have to "try it out".
And many many variables go into #temp table performance (from a sql-server SETUP, not "how you code a stored procedure". That is way outside the scope of this question.
Here is a SOF link to "safe" #temp table usage.
Temporary table in SQL server causing ' There is already an object named' error

How to replace only some Guids from a table to another, under conditions

I've created a View, but I wanted to change some of the result's Guids to Guids from another table, I want it directly in my view Result and I Don't know how?
select p.[Guid], c.[Guid] detailsGuid
INTO #temp1
from
ret_PayrollCalculationCommands s INNER JOIN
ret_PayrollCalculations p ON p.CalculationCommandGuid = s.Guid INNER JOIN
ret_vwPayrollCalculationDetails c ON c.CalculationGuid = p.Guid
you should INNER JOIN your table with same table that has target Guid column with another condition:
SELECT
p.[Guid],
c.[Guid] detailsGuid,
pMainCalculation.[Guid] AS [TargetGuid]
INTO #temp1
FROM
ret_PayrollCalculationCommands s INNER JOIN
ret_PayrollCalculations p ON p.CalculationCommandGuid = s.Guid INNER JOIN
ret_PayrollCalculations pMainCalculation ON pMainCalculation.CalculationCommandGuid = p.CalculationCommandGuid AND pMainCalculation.MainCalculation = 1 INNER JOIN
ret_vwPayrollCalculationDetails c ON c.CalculationGuid = p.Guid

Using an Inner join select statement

I am fairly new to SQL. I have created an inner join between 2 tables and further created some where clauses to pull out the appropriate data. As I understand it I have used an inner join to connect 2 tables. What I am trying to do now is connect my resultant select query to another table. How would I do this?
SELECT
t.[Type]
from [MITS].[dbo].[monster] t
inner join (
SELECT [MITS].[dbo].[BROKERTABLE].[BrokerID]
,[MITS].[dbo].[CustomerRates].[MPAN_ID]
,[MITS].[dbo].[BROKERTABLE].[Commission_Rate]
,[MITS].[dbo].[BROKERTABLE].[Rate_From]
,[MITS].[dbo].[BROKERTABLE].[Rate_To]
,[MITS].[dbo].[CustomerRates].[From_Date]
,[MITS].[dbo].[CustomerRates].[To_Date]
from [MITS].[dbo].[CustomerRates]
Inner Join [MITS].[dbo].[BROKERTABLE]
on [MITS].[dbo].[BROKERTABLE].[MPAN_ID] =
[MITS].[dbo].[CustomerRates].[MPAN_ID]
where
[MITS].[dbo].[CustomerRates].[To_Date] <=
[MITS].[dbo].[BROKERTABLE].[Rate_To]
and
convert(datetime,'01/11/2015',103)
between convert(datetime,[MITS].[dbo].[CustomerRates].[From_Date],103)
and convert(datetime,[MITS].[dbo].[CustomerRates].[To_Date],103)
) d on t.MITID = d.MPAT_ID
Add extra table into existing query: guess 1
select *
from atable a
inner join btable b on a.somecol = b.somecol
inner join extra_table t on a.somecol = t.somecol and b.somecol = t.somecol2
Add existing query to a table, method 1
select *
from extra_table t
inner join (
your existing query here
) d on t.somecol = d.somecol
Add existing query to a table, method 2
select *
from (
your existing query here
) d
inner join extra_table t on d.somecol = t.somecol

update table column using two subset query

I am using one query where i have to update one column for that i have two subset of query which is below:
select a.AuthorId as 'Source_Author',b.AuthorId as 'Target_Author' from (
select d.documentnodeid,AuthorId from wv_blogdata
inner join CMS_Document d on wv_blogdata.BlogDataID = d.DocumentForeignKeyValue
Where DocumentCulture ='en-US') a
INNER JOIN
(select d.documentnodeid,AuthorId from wv_blogdata
inner join CMS_Document d on wv_blogdata.BlogDataID = d.DocumentForeignKeyValue
Where DocumentCulture ='de-DE') b
ON a.documentnodeid =b.documentnodeid
using this query i have value like below:
Now i have to update target author with source author.
Use a common table expression
;WITH cteUpdate
AS(
select a.AuthorId as 'Source_Author',b.AuthorId as 'Target_Author'
FROM
(
SELECT d.documentnodeid,AuthorId from wv_blogdata
INNER join CMS_Document d on wv_blogdata.BlogDataID = d.DocumentForeignKeyValue
WHERE DocumentCulture ='en-US'
) a
INNER JOIN
( SELECT d.documentnodeid,AuthorId from wv_blogdata
INNER join CMS_Document d on wv_blogdata.BlogDataID = d.DocumentForeignKeyValue
WHERE DocumentCulture ='de-DE'
) b
ON a.documentnodeid =b.documentnodeid
)
UPDATE
cteUpdate
SET
cteUpdate.Target_Author = cteUpdate.Source_Author

Sum record data into one

I have this query which returns qty in each of my branch. now the branch has two WH_subType as you see in the attached diagram i have attached. I want to sum the 2 subtype and show its available qty. how can i do it.
my select query is like this
SELECT
dbo.WarehouseType.name AS Section,
dbo.WarehouseSubType.name AS WH_Type,
dbo.WarehouseSubType1.name AS WH_SubType,
dbo.Branch.name AS Branch,
(dbo.WarehouseProductQuantity.actualQuantity - dbo.WarehouseProductQuantity.reservedQuantity) AS AvailQty,
dbo.WarehouseProductQuantity.tafsilId AS Tafsil,
dbo.Tafsil.description AS Product_Name
FROM
dbo.WarehouseSubType
INNER JOIN
dbo.WarehouseType
ON
(
dbo.WarehouseSubType.warehouseTypeId = dbo.WarehouseType.id)
INNER JOIN
dbo.WarehouseSubType1
ON
(
dbo.WarehouseSubType.id = dbo.WarehouseSubType1.warehouseSubTypeId)
INNER JOIN
dbo.Warehouse
ON
(
dbo.WarehouseSubType1.id = dbo.Warehouse.warehouseSubType1Id)
INNER JOIN
dbo.Branch
ON
(
dbo.Warehouse.branchId = dbo.Branch.id)
INNER JOIN
dbo.WarehouseProductQuantity
ON
(
dbo.Warehouse.id = dbo.WarehouseProductQuantity.warehouseId)
INNER JOIN
dbo.TafsilLink
ON
(
dbo.WarehouseProductQuantity.tafsilId = dbo.TafsilLink.sourceId)
INNER JOIN
dbo.Tafsil
ON
(
dbo.TafsilLink.targetId = dbo.Tafsil.id)
INNER JOIN
dbo.FinishProduct
ON
(
dbo.Tafsil.id = dbo.FinishProduct.tafsilId)
INNER JOIN
dbo.Supplier
ON
(
dbo.FinishProduct.supplierId = dbo.Supplier.tafsilId)
WHERE
WarehouseSubType1.warehouseSubTypeId IN (1,4)
group by dbo.WarehouseProductQuantity.tafsilId
Have you tried a group by
SELECT SubType, SUM(qty) AS QtySum
GROUP BY SubType
Every grouped by column should be in your select. Note: for every column you group by it further sub divides the data
Update based on OP comment:
If you want other columns you need to do something like
SELECT s.WH_SubType,s.AvailQty, t.other_cols
from
(SELECT
dbo.WarehouseSubType1.name AS WH_SubType,
sum(dbo.WarehouseProductQuantity.actualQuantity - dbo.WarehouseProductQuantity.reservedQuantity) AS AvailQty
FROM
table
GROUP BY
dbo.WarehouseSubType1.name) s
left join table t on t.dbo.WarehouseSubType1.name = s.WH_SubType;
For reference see this question: How do I use "group by" with three columns of data?
UPDATE 2:
SELECT
dbo.WarehouseType.name AS Section,
dbo.WarehouseSubType.name AS WH_Type,
dbo.WarehouseSubType1.name AS WH_SubType,
dbo.Branch.name AS Branch,
SumTable.AvailQty,
SumTable.Tafsil,
dbo.Tafsil.description AS Product_Name
FROM
dbo.WarehouseSubType
INNER JOIN
dbo.WarehouseType
ON
(
dbo.WarehouseSubType.warehouseTypeId = dbo.WarehouseType.id)
INNER JOIN
dbo.WarehouseSubType1
ON
(
dbo.WarehouseSubType.id = dbo.WarehouseSubType1.warehouseSubTypeId)
INNER JOIN
dbo.Warehouse
ON
(
dbo.WarehouseSubType1.id = dbo.Warehouse.warehouseSubType1Id)
INNER JOIN
dbo.Branch
ON
(
dbo.Warehouse.branchId = dbo.Branch.id)
INNER JOIN
dbo.WarehouseProductQuantity
ON
(
dbo.Warehouse.id = dbo.WarehouseProductQuantity.warehouseId)
INNER JOIN
dbo.TafsilLink
ON
(
dbo.WarehouseProductQuantity.tafsilId = dbo.TafsilLink.sourceId)
INNER JOIN
dbo.Tafsil
ON
(
dbo.TafsilLink.targetId = dbo.Tafsil.id)
INNER JOIN
dbo.FinishProduct
ON
(
dbo.Tafsil.id = dbo.FinishProduct.tafsilId)
LEFT JOIN (SELECT
sum(dbo.WarehouseProductQuantity.actualQuantity - dbo.WarehouseProductQuantity.reservedQuantity) AS AvailQty,
dbo.WarehouseProductQuantity.tafsilId AS Tafsil
FROM
dbo.WarehouseProductQuantity
group by dbo.WarehouseProductQuantity.tafsilId) SumTable on dbo.Tafsil.id = SumTable.Tafsil
WHERE
WarehouseSubType1.warehouseSubTypeId IN (1,4)
You need to do something like
SELECT SUM(AvailQty), ... FROM ... WHERE ... GROUP BY WH_SubType
http://www.w3schools.com/sql/sql_func_sum.asp
http://www.w3schools.com/sql/sql_groupby.asp