将值从一个表插入到SQL Server中的另一个表

时间:2018-10-29 03:01:56

标签: sql-server insert

我有下面的表,我想将值从另一个表(旧系统)插入employeenew和部门表中,以满足新的要求。

Employeenew`(目标表)

Create table Employeenew(empo int, empname varchar(50))

部门新

Create table Departmentnew(Dname varchar(50),Location varchar(50))

当前,我在旧系统中使用这些表:

Create table tables(id int, tableid int, tablename varchar(20))

insert into tables 
values (1, 101, 'Employee'), (2, 102, 'Department')

此表包含列详细信息和表ID详细信息:

Create table fields (id int, fieldid int, fieldname varchar(20), fieldtype varchar(100), tableid int)

insert into fields  
values (1, 1001, 'empno', 'int', 101),
       (2, 1002, 'empname', 'varchar(50)', 101),
       (3, 1003, 'dname', 'varchar(50)', 102),
       (4, 1004, 'loc', 'varchar(50)', 102);

下表包含实体(行)详细信息。每行包含一个实体ID

Create table entitylistings (id int, entityid int, tableid int)

insert into entitylistings 
values (1, 10001, 101), (2, 10002, 101), (3, 10003, 102),(4, 10004, 102)

下表包含每一行的列值。

Create table tablecontents(id int, fieldid int, entityid int, value varchar(max))

insert into tablecontents
values (1, 1001, 10001, 501), (2, 1002, 10001, 'PAUL'),
       (3, 1001, 10002, 502), (4, 1002, 10002, 'RAJ'),
       (5, 1003, 10003, 'Computer'), (6, 1004, 10003, 'usa')
       (7, 1003, 10004, 'Physics'),(8, 1004, 10004, 'India')

必填输出

我想将记录从员工明细表(empno,ename)的表内容表插入Employeenew表(目标表),并从部门明细表(dname,位置)的表目录中插入Departmentnew(目标表)

输出

Employeenew Table

EMPNO      EMPNAME
501        PAUL
502        RAJ

部门新

Dname      Location
Computer   USA
Physics    INDIA   

3 个答案:

答案 0 :(得分:1)

我已经在此处使用“自我连接”来获取请求的输出。

Insert into Employeenew(empo,EMPNAME)
  Select A.Value , B.value  from tablecontents A
  INNER JOIN tablecontents B ON A.entityid=B.entityid Where ISnumeric(A.value)=1 
  and ISNUMERIC(B.Value)=0;

select * from Employeenew

答案 1 :(得分:1)

declare @fields table(id int, fieldid int, fieldname varchar(20), fieldtype varchar(100), tableid int)

insert into @fields  
values (1, 1001, 'empno', 'int', 101),
       (2, 1002, 'empname', 'varchar(50)', 101),
       (3, 1003, 'deptno', 'int', 102),
       (4, 1004, 'dname', 'varchar(50)', 102);




declare  @tablecontents table (id int, fieldid int, entityid int, value varchar(max));

insert into @tablecontents
values (1, 1001, 10001, '501'), (2, 1002, 10001, 'PAUL'),
       (3, 1001, 10002, '502'), (4, 1002, 10002, 'RAJ'),
       (5, 1003, 10003, '10'), (6, 1004, 10003, 'computer');

with data as
(
select f.fieldname, c.value, c.entityid 
from @tablecontents c
     join @fields f
        on c.fieldid = f.fieldid
where f.fieldname in ('empno', 'empname')
)

select [empno], [empname]
from data d pivot (max(value) for fieldname in ([empno], [empname]))p;

答案 2 :(得分:0)

<TextView
    ...
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:text="This is a received "/>