简体   繁体   中英

Error in Sql Query in MS Access Database?

Am trying to access 2 tables values to single query. For Eg Customer name, id, Address to a single query. Customer address - State & Country in another table Am trying to access all address to a single column in the query. In Customer table state and country code only stored. Now I can able to access Customer name, Id, Address(Single column) all in query but cont able to access that State & Country.

SELECT CustomerName, CustomerId,  (BFlatNo +','+ BPremises +','+ BStreet +','+ BArea +','+ BLocation +','+ BCity +','+ BState +','+ BCountry)  as Address FROM Customer WHERE CustomerId=11;

this code working successful & got result this 在此处输入图片说明 Am getting 24 and 1 are id's of State & Country.

so Again I modify this code to get exact address in a single column state delhi instead off 24 and country india instead of 1

SELECT CustomerName, CustomerId,  (BFlatNo +','+ BPremises +','+ BStreet +','+ BArea +','+ BLocation +','+ BCity +','+ BState +','+ (select CountryName from Country where CountryIdId=Customer.Country) AS Country)  AS Address FROM Customer;

this code showing syntax error ! How to solve this ?

If you want to SELECT from multiple tables then include the tables in the FROM clause or use a JOIN .

SELECT CustomerName,
       CustomerId,
       (BFlatNo & ',' & BPremises & ',' & BStreet & ',' & BArea & ',' & BLocation & ',' & BCity & ',' & BState & ',' & CountryName) AS Address
FROM   Customer
       INNER JOIN
       Country
       ON Country.CountryId = Customer.Country;

I'm not sure about MS Access syntax vs. SQL Server, but you can give this a shot:

SELECT 
CustomerName, 
CustomerId,  
(
(BFlatNo +','+ BPremises +','+ BStreet +','+ BArea +','+ BLocation +','+ BCity +','+ BState)
+','+
(select top 1 CountryName from Country where CountryIdId=Customer.Country)
)
AS Address 

FROM Customer;

Basically you don't need to say "as Country" as you're doing in the subquery, and you should return the top 1 result because if there are more results this will cause a problem.

Your Query to solve your problem

SELECT CustomerName, CustomerId, (BFlatNo +','+ BPremises +','+ BStreet +','+ BArea +','+ BLocation +','+ BCity +','+ BState +','+ (select CountryName from Country where CountryIdId=Customer.Country) ) AS Address FROM Customer;

You should do like this

SELECT A.CustomerName,
   A.CustomerId,
   (A.BFlatNo + ',' + A.BPremises + ',' + A.BStreet + ',' + A.BArea + ',' + A.BLocation + ',' +    A.BCity + ',' + A.BState + ',' + B.CountryName) AS Address
 FROM   Customer A, Country B 
 WHERE  B.CountryId = A.Country;

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