I'm trying to update a set of records in a table with values from within results of a subquery. When I run this query, I get error:
Msg 4104, Level 16, State 1, Line 75
The multi-part identifier be_prsn.prsn_id could not be bound.
Code:
UPDATE be_org
SET org_id = 322
WHERE be_prsn.prsn_id IN (SELECT prsn.prsn_id
FROM be_prsn prsn
JOIN be_mbr mbr ON mbr.prsn_id = prsn.prsn_id
JOIN be_empt_hist empt ON empt.mbr_id = mbr.mbr_id
LEFT JOIN be_org org ON empt.org_id = org.org_id
OUTER APPLY
(SELECT
acct.acct_id, pln.pln_sys_cd,
COUNT(pyrl.pyrl_id) AS NumPyrl
FROM
be_mbr_acct acct
JOIN
be_pstn_hist pstn ON acct.pln_id = pstn.pln_id
JOIN
be_pln pln ON acct.pln_id = pln.pln_id
LEFT JOIN
be_pyrl pyrl ON pyrl.pstn_hist_id = pstn.pstn_hist_id
WHERE
acct.mbr_id = mbr.mbr_id
AND pstn.empt_hist_id = empt.empt_hist_id
AND EXISTS (SELECT 1 FROM be_cntrb cntrb
WHERE cntrb.pyrl_id = pyrl.pyrl_id
AND cntrb.rvrs_in = 0)
GROUP BY
acct.acct_id, pln.pln_sys_cd) acct
WHERE
prsn.prsn_id = 7286);
You update attribute org_id of table be_org. So actually an attribute from another table be_prsn (I assume that's what you want to express) isn't meaningful in this context. If you wanted to include another table in your where-condition, you would have to join that other table with be_org.
you have be_prsn alias in where's nested select and use be_prsn.prsn_id on parent level. there you have only be_org
You should do join
I keep receiving the error
Msg 8156, Level 16, State 1, Line 5
The column 'Id' was specified multiple times for 'sv2017'.
Msg 8156, Level 16, State 1, Line 7
The column 'Id' was specified multiple times for 'sv2010'.
with the following script:
select
sv2017.id, sv2017.TotalArea, sv2017.uarn,
sv2010.id, sv2010.PlantMachineryValue, sv2017.PlantMachineryValue,
sv2010.uarn, sv2017.BAReferenceNumber
from
(select *
from summaryvaluation sv
join SummaryValuationPlant svp on sv.id = svp.SummaryValuationId
where sv.yearid = 2
and sv.id in (select id /*Get the most recent valuation for the list year*/
from
(select
id, uarn,
rank() over (partition by uarn order by fromdate desc) as RankOrder
from
summaryvaluation
where
yearid = 2 and systemactive = 1) tbl
where
rankorder = 1)) sv2017
left outer join
(select *
from summaryvaluation sv2
join SummaryValuationPlant svp2 on sv2.id = svp2.SummaryValuationId
where sv2.yearid = 1
and sv2.id in (select id /*Get the most recent valuation for the list year*/
from
(select
id, uarn,
rank() over (partition by uarn order by fromdate desc) as RankOrder
from
summaryvaluation
where
yearid = 1 and systemactive = 1) tbl
where
rankorder = 1)) sv2010 on sv2017.uarn = sv2010.uarn
where
isnull (sv2017.PlantMachineryValue, 0) > isnull(sv2010.PlantMachineryValue, 0)
and I can not see where I am going wrong! It is probably obvious and my brain is just not functioning but any help is appreciated.
Thanks
Your problem is probably here:
select *
from summaryvaluation sv
join SummaryValuationPlant svp
That code appears in 2 different places (with different aliases). Regardless, I suspect both tables have an id column, so when you use this in a derived table, SQL doesn't know if you are referring to the one from the sv table or the svp table.
To correct this problem, remove the * and list just those columns you will be using elsewhere in the larger query.
I have been at this for some time and am frustrated. Below is the complete SQL statement I am trying to execute. Simply put, create a temp table from a UNION Select(s) statements.
I can run the SELECTs with the UNION just fine. I can run the separate SELECTS just fine. I can run separate INSERT INTOs just fine. The moment I add an INSERT INTO SELECT * FROM (...) at the top and close it at the bottom I get a syntax error:
Msg 102, Level 15, State 1, Line 75
Incorrect syntax near ')'.
I was hoping this would be simple, but I tried everything I know to get this to work, and cannot. is there something, perhaps with the UNION that creates the syntax error?
INSERT INTO #Tmp6 SELECT * FROM
(
SELECT
[ItemStatus]
,[Item_Number]
,[Item_Name]
,[Default_Sales_Name]
,[Special_Order_Item]
,[Returnable]
,[Return_Number_Of_Days]
,[Is_Drop_Ship]
,[Is_JIT]
,[Vendor_Name]
,[Vendor_Number]
,[Default_Sales_Price]
,[Cost_Of_Goods]
,[Purchase_Cost]
,[Additional_Cost1_Text]
,[Additional_Cost1_Value]
,[Additional_Cost2_Text]
,[Additional_Cost2_Value]
,[Additional_Cost3_Text]
,[Additional_Cost3_Value]
,[UPC_Value]
,[Weight]
,[DimWeight]
,[Discontinued_Date]
,[Personalization_Template_Number]
,[Harmonized_Code]
,[Base_Category]
,[Sub_Category]
,[End_Category]
,[RowID]
FROM [dbo].[RAIProductsStg] p
WHERE ItemStatus <> 'Discontinued' OR
p.Item_Number IN (SELECT i.Item_Number FROM RAIInventoryStg i WHERE p.Item_Number = i.Item_Number AND Quantity > 0)
UNION
SELECT
[ItemStatus]
,[Item_Number]
,[Item_Name]
,[Default_Sales_Name]
,[Special_Order_Item]
,[Returnable]
,[Return_Number_Of_Days]
,[Is_Drop_Ship]
,[Is_JIT]
,[Vendor_Name]
,[Vendor_Number]
,[Default_Sales_Price]
,[Cost_Of_Goods]
,[Purchase_Cost]
,[Additional_Cost1_Text]
,[Additional_Cost1_Value]
,[Additional_Cost2_Text]
,[Additional_Cost2_Value]
,[Additional_Cost3_Text]
,[Additional_Cost3_Value]
,[UPC_Value]
,[Weight]
,[DimWeight]
,[Discontinued_Date]
,[Personalization_Template_Number]
,[Harmonized_Code]
,[Base_Category]
,[Sub_Category]
,[End_Category]
,[RowID]
FROM [dbo].[RAIProductsStg] p
LEFT JOIN RAIParentChildStg pc ON p.Item_Number = pc.ParentItemNumber
WHERE(LEN(p.Item_Number) = 6 AND p.ItemStatus = 'Discontinued') AND
(pc.ChildItemNumber IN
(SELECT i.Item_Number FROM RAIInventoryStg i
WHERE pc.ChildItemNumber = i.Item_Number AND i.Quantity > 0))
)
Please try this. Put alias after last bracket.
INSERT INTO #Tmp6
SELECT * FROM
(
SELECT
[ItemStatus]
,[Item_Number]
,[Item_Name]
,[Default_Sales_Name]
,[Special_Order_Item]
,[Returnable]
,[Return_Number_Of_Days]
,[Is_Drop_Ship]
,[Is_JIT]
,[Vendor_Name]
,[Vendor_Number]
,[Default_Sales_Price]
,[Cost_Of_Goods]
,[Purchase_Cost]
,[Additional_Cost1_Text]
,[Additional_Cost1_Value]
,[Additional_Cost2_Text]
,[Additional_Cost2_Value]
,[Additional_Cost3_Text]
,[Additional_Cost3_Value]
,[UPC_Value]
,[Weight]
,[DimWeight]
,[Discontinued_Date]
,[Personalization_Template_Number]
,[Harmonized_Code]
,[Base_Category]
,[Sub_Category]
,[End_Category]
,[RowID]
FROM [dbo].[RAIProductsStg] p
WHERE ItemStatus <> 'Discontinued' OR
p.Item_Number IN (SELECT i.Item_Number FROM RAIInventoryStg i WHERE p.Item_Number = i.Item_Number AND Quantity > 0)
UNION
SELECT
[ItemStatus]
,[Item_Number]
,[Item_Name]
,[Default_Sales_Name]
,[Special_Order_Item]
,[Returnable]
,[Return_Number_Of_Days]
,[Is_Drop_Ship]
,[Is_JIT]
,[Vendor_Name]
,[Vendor_Number]
,[Default_Sales_Price]
,[Cost_Of_Goods]
,[Purchase_Cost]
,[Additional_Cost1_Text]
,[Additional_Cost1_Value]
,[Additional_Cost2_Text]
,[Additional_Cost2_Value]
,[Additional_Cost3_Text]
,[Additional_Cost3_Value]
,[UPC_Value]
,[Weight]
,[DimWeight]
,[Discontinued_Date]
,[Personalization_Template_Number]
,[Harmonized_Code]
,[Base_Category]
,[Sub_Category]
,[End_Category]
,[RowID]
FROM [dbo].[RAIProductsStg] p
LEFT JOIN RAIParentChildStg pc ON p.Item_Number = pc.ParentItemNumber
WHERE(LEN(p.Item_Number) = 6 AND p.ItemStatus = 'Discontinued') AND
(pc.ChildItemNumber IN
(SELECT i.Item_Number FROM RAIInventoryStg i
WHERE pc.ChildItemNumber = i.Item_Number AND i.Quantity > 0))
)c
Place the bracket after the second select statement. That should do it.
INSERT INTO TableA
(
SELECT A, B, C
FROM TableB
UNION
SELECT D, E, F
FROM TableC
)
I am trying to update data using this update query....not inserting. but i am getting this error message. How to fix this
Msg 2627, Level 14, State 1, Procedure
BF_TR_BUDCONTRACTS_HISTORY_INSERTUPDATE, Line 67 Violation of UNIQUE
KEY constraint 'UK_BudContractHis'. Cannot insert duplicate key in
object 'dbo.BUDCONTRACTS_HISTORY'. The duplicate key value is (10567,
4377, 228, 1). The statement has been terminated.
Update BUDCONTRACTS
set BUDCONTRACTS.VERSIONID = 1
,BUDCONTRACTS.STATUSID = 1
,BUDCONTRACTS.ImportedRecord = 1
,BUDCONTRACTS.CUSTOMERID = BCUST.CustomerID
,BUDCONTRACTS.LastModifiedUserID = 'Import'
,BUDCONTRACTS.LASTMODIFIEDDATETIME = GETDATE()
FROM BUDCONTRACTS BCON
INNER JOIN External_Blk_Itm_Contracts EBIC WITH(NOLOCK) ON BCON.ContractName = EBIC.ContractName AND EBIC.ContractName = '00-000'
INNER JOIN BUDTERMINALS BT WITH(NOLOCK) ON BT.MBFTERMINALNAME = EBIC.TerminalName AND BT.TERMINALID = BCON.TERMINALID
INNER JOIN BudCustomers BCUST WITH(NOLOCK) ON BCUST.LegalName = EBIC.CustomerName AND BCUST.CustomerID = BCON.CUSTOMERID
AND (
(BCON.STATUSID <> 1)
OR (BCON.ImportedRecord <> 1)
OR (ISNULL(BCON.CUSTOMERID,'') <> ISNULL(BCUST.CustomerID,'')
))
I had the same problem and it turned out I didn't have enough keys in the update statement to only update 1 record when I ran the query it returned more than 1 row and the update failed. This was good as I had changed the clustered index for the extra field.
Here is a better way to write this update.
Update BCON
set VERSIONID = 1
, STATUSID = 1
, ImportedRecord = 1
, CUSTOMERID = BCUST.CustomerID
, LastModifiedUserID = 'Import'
, LASTMODIFIEDDATETIME = GETDATE()
FROM BUDCONTRACTS BCON
INNER JOIN External_Blk_Itm_Contracts EBIC ON BCON.ContractName = EBIC.ContractName AND EBIC.ContractName = '00-000'
INNER JOIN BUDTERMINALS BT ON BT.MBFTERMINALNAME = EBIC.TerminalName AND BT.TERMINALID = BCON.TERMINALID
INNER JOIN BudCustomers BCUST ON BCUST.LegalName = EBIC.CustomerName AND BCUST.CustomerID = BCON.CUSTOMERID
AND
(
BCON.STATUSID <> 1
OR
BCON.ImportedRecord <> 1
)
--OR ISNULL(BCON.CUSTOMERID,'') <> ISNULL(BCUST.CustomerID,'' This is pointless here because you already joined where these values are equal
Now for the actual issue. You are not referencing dbo.BUDCONTRACTS_HISTORY in this query so it is obvious there is an UPDATE trigger on BUDCONTACTS. That is where the problem is happening. It is probably trying to insert a row into the history table but there is already a row with the key value so it is unable to insert that row. If you can post the trigger code and the table definition for dbo.BUDCONTRACTS_HISTORY we can help you straighten out the trigger.
When I run the following query against a MSSQL 2000
SELECT
DISTINCT(Email),
(SELECT TOP 1 ActivityID
FROM Activity aa, ActivityType tt
WHERE aa.ActivityTypeId = tt.ActivityTypeId
AND aa.ConsumerID = c.ConsumerID
AND tt.ActivityType = 'Something_OptIn') optin,
(SELECT TOP 1 ActivityID
FROM Activity aa, ActivityType tt
WHERE aa.ActivityTypeId = tt.ActivityTypeId
AND aa.ConsumerID = c.ConsumerID
AND tt.ActivityType = 'Something_OptOut') optout
FROM
Activity a,
Consumer c,
ActivityType t
WHERE
c.CountryID = '23'
AND t.ActivityType = 'Something_Create'
AND a.ActivityTypeId = t.ActivityTypeId
AND c.ConsumerID = a.ConsumerID
AND optin > 1
I get the following error
Server: Msg 207, Level 16, State 3, Line 1
Invalid column name 'optin'.
Why does this happen? I can't see why it would be invalid.
SQL Server does not allow you to refer to aliases by name at the same level. To fix this, repeat the column definition:
WHERE
c.CountryID = '23'
AND t.ActivityType = 'Something_Create'
AND a.ActivityTypeId = t.ActivityTypeId
AND c.ConsumerID = a.ConsumerID
AND (SELECT TOP 1 ActivityID
FROM Activity aa, ActivityType tt
WHERE aa.ActivityTypeId = tt.ActivityTypeId
AND aa.ConsumerID = c.ConsumerID
AND tt.ActivityType = 'Something_OptIn'
) > 1
Or use a subquery:
SELECT *
FROM (
SELECT
DISTINCT(Email),
(...) optin,
(...) optout
FROM
Activity a,
Consumer c,
ActivityType t
) as SubqueryAlias
WHERE
c.CountryID = '23'
AND t.ActivityType = 'Something_Create'
AND a.ActivityTypeId = t.ActivityTypeId
AND c.ConsumerID = a.ConsumerID
AND optin > 1
The last line AND optin > 1 is the offender.
The WHERE clause knows nothing about column aliases in the SELECT list.
You should probably subquery this SELECT without the offending condition, and apply that condition to the outer SELECT.
SELECT *
FROM (
SELECT
...
WHERE ... /* everything except 'optin > 1' */
) anyAlias
WHERE optin > 1