Multi-Part Identifier in SQL Temp Table - sql

I am trying to insert values from an exisiting table into a temp table. However, I just want the values from one table which equal the value of another table to be inserted into my temp table (sorry if that was confusing)
Here is my code:
select * into
#gl_chart_av
from glchart where glchart.account_code = AdaptInvalidAccts.account_code
I'd like just the data from the glchart table inserted into my temp table who's account code in the glchart table matches that of the account codes found in the AdaptInvalidAccts table. But, I get a multi-part identifier error. Does anyone know how I can fix this?

This sounds like a case where you would use an EXISTS. It will only return records from glchart that are present in AdaptInvalidAccts based on the account_code matching.
select *
into #gl_chart_av
from glchart
where EXISTS (
SELECT 1
FROM AdaptInvalidAccts
WHERE glchart.account_code = AdaptInvalidAccts.account_code)
As for the identifier error, nowhere in your code are you declaring the AdaptInvalidAccts alias on AdaptInvalidAccts.account_code

select glchart.*
into #gl_chart_av
from
glchart
inner join AdaptInvalidAccts on glchart.account_code=AdaptInvalidAccts.account_code
or
select *
into #gl_chart_av
from glchart
where account_code in (
select account_code from AdaptInvalidAccts
)

Related

Postgresql, Copy data to a new table from a foreign table

I'm trying to do a job that will copy data from a foreign table called "m_aduana" of the schema "nathalia" to my schema "publico" and my table "mae_aduana".
I need to do a query that copies all the values from the table "m_aduana" avoiding duplicates.
I got something like this for now but the result sends me an Insert 0 0, which means nothing is inserted.
insert into publico.mae_aduana(cod_aduana,nom_aduana,des_aduana,cod_aduana1,cod_aduana2,cod_aduana3,est_aduana)
select cod_aduana,nom_aduana,des_aduana,cod_aduana1,cod_aduana2,cod_aduana3,est_aduana
from nathalia.m_aduana
where not exists (
select * from publico.mae_aduana ma_ad, nathalia.m_aduana m_ad
where ma_ad.cod_aduana = m_ad.cod_aduana)
I think you have an error in the inner select. You don't need to use again the table nathalia.m_aduana. If should be something like:
insert into publico.mae_aduana(cod_aduana,nom_aduana,des_aduana,cod_aduana1,cod_aduana2,cod_aduana3,est_aduana)
select cod_aduana,nom_aduana,des_aduana,cod_aduana1,cod_aduana2,cod_aduana3,est_aduana
from nathalia.m_aduana
where not exists (
select * from publico.mae_aduana ma_ad
where ma_ad.cod_aduana = nathalia.m_aduana.cod_aduana)
You might want to change the where exists part like below
from nathalia.m_aduana m
where not exists (
select 1 from publico.mae_aduana
where cod_aduana = m.cod_aduana)

How to create temp table in postgresql with values and empty column

I am very new to postgresql. I want to create a temp table containing some values and empty columns. Here is my query but it is not executing, but gives an error at , (comma).
CREATE TEMP TABLE temp1
AS (
SELECT distinct region_name, country_name
from opens
where track_id=42, count int)
What did I do wrong?
How to create a temp table with some columns that has values using select query and other columns as empty?
Just select a NULL value:
CREATE TEMP TABLE temp1
AS
SELECT distinct region_name, country_name, null::integer as "count"
from opens
where track_id=42;
The cast to an integer (null::integer) is necessary, otherwise Postgres wouldn't know what data type to use for the additional column. If you want to supply a different value you can of course use e.g. 42 as "count" instead
Note that count is a reserved keyword, so you have to use double quotes if you want to use it as an identifier. It would however be better to find a different name.
There is also no need to put the SELECT statement for an CREATE TABLE AS SELECT between parentheses.
Your error comes form your statement near the clause WHERE.
This should work :
CREATE TEMP TABLE temp1 AS
(SELECT distinct region_name,
country_name,
0 as count
FROM opens
WHERE track_id=42)
Try This.
CREATE TEMP TABLE temp1 AS
(SELECT distinct region_name,
country_name,
cast( '0' as integer) as count
FROM opens
WHERE track_id=42);

SQL Query to match if data is not present in another table

I have two tables named tblStockManagement and tblFolding in my database. i have column Name in tblFolding table and column FoldingID as Foreign Key in tblStockManagement table. now i have comboBox in my Winform and i want Names of Items in combobox from tblFolding Table but only those items that are not in tblStockManagement Table.
(because i dont want to select data again if it is already in tblStockManagement table . instead i will update the quantity later).
these are the screenshots of both of tables. please tell me how can i do that
NOT EXISTS version:
select *
from tblFolding f
where not exists (select * from tblStockManagement SM
where sm.FoldingID = f.FoldingID)
NOT EXISTS is "NULL safe", which NOT IN isn't.
This is you need.Basically a sub query which gets all folding id and using not in operator I exclude those matching sets.
SELECT Name
FROM tblFolding
WHERE FoldingID NOT IN (
SELECT FoldingID
FROM tblStockManagement
)
;
You can use SQL NOT condition
Select Name
From tblFolding
Where FoldingId Not In (Select FoldingId From tblStockManagement)
Order By Name

SQL IN query produces strange result

Please see the table structure below:
CREATE TABLE Person (id int not null, PID INT NOT NULL, Name VARCHAR(50))
CREATE TABLE [Order] (OID INT NOT NULL, PID INT NOT NULL)
INSERT INTO Person VALUES (1,1,'Ian')
INSERT INTO Person VALUES (2,2,'Maria')
INSERT INTO [Order] values (1,1)
Why does the following query return two results:
select * from Person WHERE id IN (SELECT ID FROM [Order])
ID does not exist in Order. Why does the query above produce results? I would expect it to error because I'd does not exist in order.
This behavior, while unintuitive, is very well defined in Microsoft's Knowledge Base:
KB #298674 : PRB: Subquery Resolves Names of Column to Outer Tables
From that article:
To illustrate the behavior, use the following two table structures and query:
CREATE TABLE X1 (ColA INT, ColB INT)
CREATE TABLE X2 (ColC INT, ColD INT)
SELECT ColA FROM X1 WHERE ColA IN (Select ColB FROM X2)
The query returns a result where the column ColB is considered from table X1.
By qualifying the column name, the error message occurs as illustrated by the following query:
SELECT ColA FROM X1 WHERE ColA in (Select X2.ColB FROM X2)
Server: Msg 207, Level 16, State 3, Line 1
Invalid column name 'ColB'.
Folks have been complaining about this issue for years, but Microsoft isn't going to fix it. It is, after all, complying with the standard, which essentially states:
If you don't find column x in the current scope, traverse to the next outer scope, and so on, until you find a reference.
More information in the following Connect "bugs" along with multiple official confirmations that this behavior is by design and is not going to change (so you'll have to change yours - i.e. always use aliases):
Connect #338468 : CTE Column Name resolution in Sub Query is not validated
Connect #735178 : T-SQL subquery not working in some cases when IN operator used
Connect #302281 : Non-existent column causes subquery to be ignored
Connect #772612 : Alias error not being reported when within an IN operator
Connect #265772 : Bug using sub select
In your case, this "error" will probably be much less likely to occur if you use more meaningful names than ID, OID and PID. Does Order.PID point to Person.id or Person.PID? Design your tables so that people can figure out the relationships without having to ask you. A PersonID should always be a PersonID, no matter where in the schema it is; same with an OrderID. Saving a few characters of typing is not a good price to pay for a completely ambiguous schema.
You could write an EXISTS clause instead:
... FROM dbo.Person AS p WHERE EXISTS
(
SELECT 1 FROM dbo.[Order] AS o
WHERE o.PID = p.id -- or is it PID? See why it pays to be explicit?
);
The problem here is that you're not using Table.Column notation in your subquery, table Order doesn't have column ID and ID in subquery really means Person.ID, not [Order].ID. That's why I always insist on using aliases for tables in production code. Compare these two queries:
select * from Person WHERE id IN (SELECT ID FROM [Order]);
select * from Person as p WHERE p.id IN (SELECT o.ID FROM [Order] as o)
The first one will execute but will return incorrect results, and the second one will raise an error. It's because the outer query's columns may be referenced in a subquery, so in this case you can use Person columns inside the subquery.
Perhaps you wanted to use the query like this:
select * from Person WHERE pid IN (SELECT PID FROM [Order])
But you never know when the schema of the [Order] table changes, and if somebody drops the column PID from [Order] then your query will return all rows from the table Person. Therefore, use aliases:
select * from Person as P WHERE P.pid IN (SELECT O.PID FROM [Order] as O)
Just quick note - this is not SQL Server specific behaviour, it's standard SQL:
SQL Server demo
PostgreSQL demo
MySQL demo
Oracle demo
Order table doesnt have id column
Try these instead:
select * from Person WHERE id IN (SELECT OID FROM [Order])
OR
select * from Person WHERE pid IN (SELECT PID FROM [Order])

SQL Insert/Update Issue

I am trying to update one table from another, im able to update fine as long as the customer record exists, but there are some entries that dont.
To solve this i've tried running the following insert
SELECT *
INTO SalBudgetCust
FROM SalBudgetCust_temp
WHERE NOT EXISTS (
SELECT Customer
FROM SalBudgetCust
WHERE Customer = SalBudgetCust_temp.Customer
)
but im prompted with
There is already an object named 'SalBudgetCust' in the database.
Im stuck at this point... could anyone offer a little guideance?
SELECT INTO implicitly creates the table you name. You should instead use INSERT INTO ... SELECT * FROM ..., so that the existing table is used.
It should be INSERT INTO instead of SELECT * INTO ... like
INSERT INTO SalBudgetCust SELECT * FROM SalBudgetCust_temp
WHERE NOT EXISTS
(
SELECT Customer FROM SalBudgetCust WHERE Customer = SalBudgetCust_temp.Customer
)
The general syntax to insert data of one table into another is :
INSERT INTO new_table
SELECT * FROM old_table
WHERE some_condition;
Where, new_table is the table where you want to insert data, old_table is table from where you are fetching data and some_condition is the expression / condition based upon which you want to fetch data from old table.
You may use other clauses like order by, group by, and even sub queries after where clause.
May refer this SQL INSERT INTO and it's subsequent pages.