简体   繁体   中英

How are you able to UNION data from SEPARATE TABLES into a TABLE VARIABLE?

I am trying to take data from two different tables and union them together into a table variable. I am working in AdventureWorks2016. So far this is what I have:

--Query 4 – Must use the UNION operator
SELECT *
FROM    Person.Address

SELECT      *
FROM        Person.StateProvince
--TABLE VARIABLE
DECLARE     @PersonAddress TABLE (Name VARCHAR(50), AddressLine NVARCHAR(50), StateProvinceID INT)
INSERT INTO @PersonAddress
SELECT  AddressLine1,StateProvinceID
FROM    Person.Address
UNION ALL
SELECT  [Name],StateProvinceID
FROM    Person.StateProvince

SELECT      *
FROM        @PersonAddress

With that Code I receive the following Error:

"Msg 205, Level 16, State 1, Line 156 All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists."

Let me know what you think. Thank You!

What you need is a join, since you are working with AdventureWorks DB, I think what you are trying to achieve is this:

    DECLARE     @PersonAddress TABLE (Name VARCHAR(50), AddressLine NVARCHAR(50), StateProvinceID INT)
    INSERT INTO @PersonAddress
    Select  PSP.Name,
            PA.AddressLine1,
            PA.StateProvinceID
    From Person.Address PA
    Join Person.StateProvince PSP ON PSP.StateProvinceID = PA.StateProvinceID
    
    SELECT      *
    FROM        @PersonAddress

the first query has two fields (AddressLine1 and City) while the second query has only one field (Name), this is what SQL Server is complaining.

What you want is to join them, not union. Since we don't have the structure of your tables, this is a guest:

INSERT INTO @PersonAddress (name, addresline, stateprovince)
SELECT  name, adressline1, stateprovince
FROM    Person.Address pa
inner join  Person.AddressType pat on pa.AddressTypeId = pa.id -- make sure to join the tables on the required fields

As said by others the union all requires identical structure for both query,

I am not clear what you want achieve (could be done by a join as one of the contributor said ) but specific to your problem you might need to do something like below,

Note: I have just used dummy table which you need to change with original ones

DECLARE     @PersonAddress TABLE (Name VARCHAR(50), AddressLine NVARCHAR(50), StateProvinceID INT)
INSERT INTO @PersonAddress
SELECT  null name,'Address 1' AddressLine1, 100 StateProvinceID
UNION ALL
SELECT  'Dummy' name,null AddressLine1,100 StateProvinceID

SELECT      *
FROM        @PersonAddress

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM