The multi-part identifier "field" could not be bound - sql-server-2012

I'm trying to use data stored in a temporary result set (SOURCE in the code) to fill another table with SQL Server 2012. When executing the below code I get the error "The multi-part identifier "SOURCE.JnlDetoaId" could not be bound".
SELECT Journaldet.*, Agency.ID_Agency INTO SOURCE
FROM Journaldet
inner join Agency
ON Agency.Agency_ID = Journaldet.AgenceId
IF ((SELECT COUNT(Journal.Journal_ID) FROM dbo.Journal, SOURCE WHERE Journal_ID = SOURCE.JournalId)=0)
INSERT INTO Discarded.JournalDet(JournalDet_ID, Amount, Sensoa, DetoaId, ID_Agency, JournalId, Appli_Source, ReasonDiscarded, DateDiscarded)
VALUES (SOURCE.JnlDetoaId, SOURCE.Amount, SOURCE.Sensoa, SOURCE.DetoaId, SOURCE.ID_Agency, JournalId, 'GameApps','Member not yet inserted', GETDATE());
I read some threads about here but didn't see how to apply them to my case.
Any help please?

SELECT Journaldet.*, Agency.ID_Agency INTO sourceTable
FROM Journaldet
inner join Agency
ON Agency.Agency_ID = Journaldet.AgenceId;
IF ((SELECT COUNT(j.Journal_ID) FROM dbo.Journal as j, sourceTable s WHERE j.Journal_ID = s.JournalId) = 0)
INSERT INTO Discarded.JournalDet(JournalDet_ID, Amount, Sensoa, DetoaId,ID_Agency, JournalId, Appli_Source, ReasonDiscarded, DateDiscarded)
VALUES (select JnlDetoaId, Amount, Sensoa, DetoaId, ID_Agency, JournalId, 'GameApps','Member not yet inserted', GETDATE() FROM sourceTable)
The problem was in you insert () values().
To insert values into your Discarded.JournalDet table. You cannot just use the above fields from source table. You have to select from the source table.
U cannot just user the source.JournalDet .. and soo on , directly only because they are defined few line above.

Below is how I solved my issue. The SOURCE was not seen in the INSERT as a result set as I wanted. It was nothing for the INSERT. I just rewrote the queries in such a way that the result set be seen in the INSERT. Thanks a lot user2919277.
INSERT INTO Discarded.JournalDet
(JournalDet_ID, Amount, Sensoa, DetoaId, ID_Agency, JournalId, Appli_Source, ReasonDiscarded, DateDiscarded)
SELECT SOURCE1.JnlDetoaId, Amount,Sensoa,DetoaId,ID_Agency,JournalId, 'GameApps', 'Member not yet inserted', GETDATE()
FROM Journaldet AS SOURCE1
inner join Agency AS SOURCE2 ON SOURCE2.Agency_ID = SOURCE1.AgenceId
WHERE ((SELECT COUNT(Journal.Journal_ID) FROM dbo.Journal WHERE dbo.Journal.Journal_ID = SOURCE1.JournalId)=0)

Related

Update table setting the value of a field to the result of a query

I have the following table(let's call it Sales) structure:
What I would like to do is to fill the field "SalesID" with values resulting from a query I have created in the same DB. This query reflects the table structure so I was thinking to connect the two using the ID.
Basically, I am trying with scripts of this forms:
UPDATE Sales
SET SalesID = ( SELECT SalesIDCalc FROM (SELECT Sales.ID, Sales.[Email Address], Sales.[Points], IIf([Points] >80,"Super","Normal") AS SalesIDCalc FROM Sales) AS q
WHERE Sales.ID = q.ID);
but I am nowhere near the solution. Do you have any idea on how to proceed?
EDIT: Now I get the Error 'Operation must use an updateable table'
I think you want UPDATE with a correlated subquery:
UPDATE Sales
SET SalesID = (SELECT SalesIDCalc
FROM (MyQuery) as q
WHERE Sales.ID = q.ID
);

Updating a lot of Data in One Field using Where clause

I am trying to update one filled with a lot of data.
This is my table
I want to update NameAlias with new names for Major but this is my question if I have a lot of major names and ids how can I write a query that is good and short?
I know it should be something like this for one column.
Update Major Set NameAlias='Mathemathic' where IdMajor=1;
But what should I do if I have a lot of data for one field?
I want my result to be something like this:
You can use case when expression -
Update Major Set NameAlias=
case when namemajor='Math' then 'Mathemathic'
when namemajor='Computer' then 'Software'
when namemajor='Art' then 'Painthing'
when namemajor='History' then 'FranceHistory'
when namemajor='Music' then 'Piano' end
You should create a temp table containing the id, NameAlias accordingly like below.
select Id, NameAlias
into #TempTable
from (
values(1, 'Mathemathic'),
(2, 'Software'),
(3, 'Painthing')
-- The rest of values
)v(Id, NameAlias)
Then you can update the Major table
Update m
SET m.NameAlias = t.NameAlias
From Major m
INNER JOIN #TempTable t on m.IdMajor = t.Id
There is no need to create a temporary table to do this. Just use a derived table in the update query:
update m
set m.NameAlias = v.newAlias
from Major m join
(values(1, 'Mathematic'),
(2, 'Software'),
(3, 'Painting')
) v(idMajor, newAlias)
on m.IdMajor = v.IdMajor;

Update largest date, matching two fields

tables
Hi, I'm looking to update the last column in a blank table. Picture shows input and desired output. Trying to pick the largest date where workorder and state match.
I've tried a couple different codes:
UPDATE mytable
SET mytable.orderstartdate = MAX(table2.earliestdate)
FROM mytable as table2
WHERE (mytable.workorder = table2.workorder AND
mytable.state = table2.state)
;
"Syntax Error (missing operator) in query expression 'MAX(table2.earliestdate) FROM mytable as table2'."
UPDATE mytable
SET mytable.orderstartdate = (
SELECT max(earliestdate)
FROM mytable as table2
WHERE (mytable.workorder = table2.workorder AND
mytable.state = table2.state)
)
;
"Operation must use an updateable query"
Edit - click tables link for image.
Write PL/SQL Code.
First, select DISTINCT WorkOrder and State and capture in variables.
Now, Iterate the list and Write a query to get max date i.e. max(date) using work_order and State in where clause. Capture the
date.
Now, In the same loop write update query setting max(date) and workorder and State in where clause.
UPDATE table A
SET A.orderstartDate = (SELECT max(earliestdate)
FROM table B
WHERE A.WorkOrder = B.WorkOrder
GROUP BY WorkOrder)
not sure if access supports correlated subqueries but if it does...
and if not...
UPDATE table A
INNER JOIN (SELECT WorkOrder, max(OrderStartDate) MOSD
FROM Table B
GROUP BY WorkOrder) C
ON A.WorkOrder = C.workOrder
SET A.OrderStartDate = C.MOSD
Check database open mode, it may be locked for editing, or you may have no permission to to file.

Insert into SELECT with composite primary key failing SQL Server 2008

I have one very large, un-normalized table which I am in the process of fixing. From that large table I'm normalizing the data. I used the SQL statement
INSERT INTO smallTable(patientID, admissionDate, dischargeDate)
select distinct patientID, admissionDate, dischargeDate
FROM largeTable
So my smallTable is populated with the correct number of rows. There's another column, drgCode that I want to add to my smallTable. I tried the following query to do that
INSERT INTO smallTable(drgCode)
select drgCode from
(
SELECT DISTINCT patientID, admissionDate, dischargeDate, drgCode from largeTable) as t
The error I was given reads cannot insert the value NULL into patientID, column does not alloq nulls, insert fails.
The only way that the drgCode will be chosen correctly is if some variant of the select distinct query is used. How can I insert only one field, when the other fields must be included to narrow down the search.
I know I could do this if I emptied out my smallTable, but I figured there's gotta be a way around it.
with drg as (SELECT DISTINCT patientID, admissionDate, dischargeDate, drgCode from largeTable)
update s
set s.drgCode = l.drgCode
from smallTable s join drg l on
s.patientId = l.patientId and
s.admissionDate = l.admissionDate and
s.dischargeDate = l.dischargeDate
As per my understanding, if you have "PatientID" to be unique in both the tables, you can do something like below.
Update S
SET S.drgCode = L.drgCode
FROM
SmallTable S
INNER JOIN
LargeTable T
ON S.PatientID = T.PatientID
Hope this Helps!!
When you perform an insert to a table, any values not specified in the query are poulated with the default value for the column. If there is no default value on the column, NULL will be used. You recieved that particular error message because your column does not allow NULL and does not have a default.
Given your reply to Praveen, perhaps you should be further normalizing and put the drgCodes into a separate table.

T-SQL Output Clause: How to access the old Identity ID

I have a T-SQL statement that basically does an insert and OUTPUTs some of the inserted values to a table variable for later processing.
Is there a way for me to store the old Identity ID of the selected records into my table variable. If I use the code below, I get "The multi-part identifier "a.ID" could not be bound." error.
DECLARE #act_map_matrix table(new_act_id INT, old_ID int)
DECLARE #new_script_id int
SET #new_script_id = 1
INSERT INTO Act
(ScriptID, Number, SubNumber, SortOrder, Title, IsDeleted)
OUTPUT inserted.ID, a.ID INTO #act_map_matrix
SELECT
#new_scriptID, a.Number, a.SubNumber, a.SortOrder, a.Title, a.IsDeleted
FROM Act a WHERE a.ScriptID = 2
Thanks!
I was having your same problem and found a solution at http://sqlblog.com/blogs/adam_machanic/archive/2009/08/24/dr-output-or-how-i-learned-to-stop-worrying-and-love-the-merge.aspx
Basically it hacks the MERGE command to use that for insert so you can access a source field in the OUTPUT clause that wasn't inserted.
MERGE INTO people AS tgt
USING #data AS src ON
1=0 --Never match
WHEN NOT MATCHED THEN
INSERT
(
name,
current_salary
)
VALUES
(
src.name,
src.salary
)
OUTPUT
src.input_surrogate,
inserted.person_id
INTO #surrogate_map;
You'll have to join back #act_map_matrix onto Act to get the "old" value.
It's simply not available in the INSERT statement
edit: one hopes that #new_scriptID and "scriptid=2" could be the join column