简体   繁体   English

插入另一个表中的值

[英]Insert values from another table

I am trying to insert into a field using the input from another table field. 我试图使用另一个表字段的输入插入字段。 Although this is entirely feasible for many database engine, 虽然这对许多数据库引擎完全可行,

I have the following fields, 我有以下字段,

New Table Schema 新表架构

  • Name 名称
  • Industryid(int) Industryid(INT)
  • Locationid(int) Locationid(INT)

But the actual records like, 但实际记录如,

  • xxxx XXXX
  • TEXT (varchar) TEXT(varchar)
  • TEXT(Varchar) TEXT(VARCHAR)

But I want these two Industryid and Locationid by id's from another table Industries, Locations. 但我希望这两个Industryid和Locationid来自另一个表,工业,地点的id。

I have another 2 tables for 我还有另外两张桌子

Industries 工业

  • Id ID
  • Name 名称

Locations 地点

  • Id ID
  • Name 名称

My Query is, 我的查询是,

select'insert into organizations(name,industryid,locationid)
values
('''+
Nameofthecompany+''','+
Isnull(industrytype,'Null')+','+
ISNULL(Location,'Null')+')' 
from Organization`

Result 结果

insert into organizations(name,industryid,locationid) 
values 
('Swamy',Telcom,Chennai)

Expected Result 预期结果

insert into organizations(name,industryid,locationid)
values
('Swamy',12,150)

If your current/actual records are already in a table named Organization as shown in your query, you can use this approach to populate your new Organizations table: 如果您的当前/实际记录已经在查询中显示的名为Organization的表中,则可以使用此方法填充新的Organizations表:

INSERT INTO Organizations( name, IndustryId, LocationId )
SELECT o.Nameofthecompany, i.Id, l.Id
FROM Organization AS o
LEFT JOIN Industries AS i ON o.industrytype = i.Name
LEFT JOIN Location AS l ON o.Location = l.Name

This takes the existing names, joins to your reference tables ( Industries and Locations ) and retrieves the Id values for the corresponding text values. 这将现有名称,连接到您的引用表( IndustriesLocations )并检索相应文本值的Id值。

The LEFT JOIN will bring back all of the names from Organization, but not require them to have a matching Industry and Location in the reference tables. LEFT JOIN将从组织中返回所有名称,但不要求它们在参考表中具有匹配的行业和位置。

You can do something like this: 你可以这样做:

SELECT Col1, Col2
INTO TestTable
FROM OriginalTable
WHERE Conditions

Notice that SELECT INTO only works if the table specified in the INTO clause does not exist 请注意,只有在INTO子句中指定的表不存在时,SELECT INTO才有效

Or: 要么:

INSERT INTO TestTable (Col1, Col2)
SELECT Col1, Col2
FROM OriginalTable
WHERE Conditions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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