2016-08-24 101 views
-1

以下是使用SQL查询插入选择,这是不工作,请与问题的帮助:MS SQL插入与选择

insert into Area Values (AreaId, AreaName, Pincode, CityId, StateId, CountryId) 
    select CityId 
    from Area 
     join City On Area.CityId = City.CityId 
     Join State on Area.StateId = State.StateId 
     join Country on Area.CountryId = Country.CountryId; 
+3

您需要选择与插入相同数量的列。 – jarlh

+0

在INSERT中选择时没有值。即'插入区域(col1,...)选择...'。 – jarlh

+0

insert into area(column1,column2)select forcolumn1,forcolumn2 from x 。你不需要“值”,因为值来自select。 –

回答

0

什么是该查询的目的是什么?您正在与其他人加入目标表(Area)并尝试插入它,这是数据已在Area表中显示的标记,并且您正在插入重复项或试图更新现在为空的列。在这种情况下,您需要合并甚至更新。

UPDATE A 
SET CityID = c.CityID, 
    StateID = s.StateID, 
    CountryID = co.CountryID 
from Area a 
join City c 
    On a.CityId = c.CityId 
Join State s 
    on a.StateId = s.StateId 
join Country co 
    on a.CountryId = co.CountryId; 

如果正是你需要插入 - 指定一个像下面的所有列:

insert into Area Values (AreaId, AreaName, Pincode, CityId, StateId, CountryId) 
select a.AreaID, 
     a.AreaName, 
     a.Pincode, 
     c.CityID, 
     s.StateID, 
     co.CountryID 
from Area a 
join City c 
    On a.CityId = c.CityId 
Join State s 
    on a.StateId = s.StateId 
join Country co 
    on a.CountryId = co.CountryId; 

编辑:

insert into Area Values (AreaId, AreaName, Pincode, CityId, StateId, CountryId) 
select a.AreaID, 
     a.AreaName, 
     a.Pincode, 
     c.CityID, 
     s.StateID, 
     co.CountryID 
from Area a 
LEFT join City c 
    On c.CityName = @CityName 
LEFT Join State s 
    on s.StateName = @StateName 
LEFT join Country co 
    on co.CountryName = @CountryName; 

@CityName@StateName@CountryName是变量存储从下拉列表数据。

+0

嗨,感谢您的回复 – balram

+0

嗨,感谢您的回复。实际上,CityId的城市表与CityName相关联,并且Cityname位于dropdownlist1中,StateId在State Table中与StateName相关联,Statename位于dropdownlist2中,CountryId在国家表中与CountryName相关联,并且Countryname位于区域执行页面中的dropdownlist3中。 – balram

+0

区域输出页面AreaId,AreaName,Pincode,CityName(dropdownlist1),StateName(dropdownlist2),CountryName(dropdownlist3);城市表(CityID,CityName);状态表(StateID,StateName);国家表(CountryID,CountryName);区域表(AreaId,AreaName,Pincode,CityId,StataId,CountryId) – balram