未加星标

Insert in 2 tables select the result of a SQL Server table

字体大小 | |
[数据库(mssql) 所属分类 数据库(mssql) | 发布者 店小二04 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏

How to insert into 2 tables result from a select statement.

I have a table with several data:

val1 val2 val3 .... valn ------------------------- 12 21 54 78 .. .. .. ..

I have something like: Select t1.val1, t1.val2, t2.val3, t2.val4 into table1 t1 , table2 t2 from tablename.

So I want val1, val2, being inserted into a new table with 2 fields like:

tabble1: id fieldvalue 1 val1 2 val2

the same goes to val3 and val4. How can this be acomplished

tabble2: id fieldvalue 1 val3 2 val4

Is this possible?

Granted, it is difficult to understand what you are trying to accomplish. If you are in fact trying to insert rows into two different tables, as marc_s stated, you must use two insert statements.

However, judging from your sample, it may not be the case that you are trying to insert into two tables but rather use two tables to insert into a third table where you transpose the data. If that is the case, then you can do it in a single statement:

Insert MysteryTable( Id, fieldvalue ) Select 1, val1 From Table1 Union All Select 2, val2 From Table1 Union All Select 3, val3 From Table2 --assuming these come from Table2. Isn't clear in the OP Union All Select 4, val4 From Table2 --assuming these come from Table2. Isn't clear in the OP

Of course, if Table1 or Table2 has many rows, then you will obviously get many rows with the same Id value in your MysteryTable.

Update given change to OP

Given your clarification, what you seek can be done but requires two queries similar to the one above.

Insert Table1( Id, fieldvalue ) Select 1, val1 From SourceTable Union All Select 2, val2 From SourceTable Insert Table2( Id, fieldvalue ) Select 1, val3 From SourceTable Union All Select 2, val4 From SourceTable

Another variation which generates your id values would be:

With NumberedItems As ( Select val1 As val From SourceTable Union All Select val2 From SourceTable ) Insert Table1(id, fieldname) Select Row_Number() Over( Order By val ) As Num , val From SourceTable With NumberedItems As ( Select val3 As val From SourceTable Union All Select val4 From SourceTable ) Insert Table2(id, fieldname) Select Row_Number() Over( Order By val ) As Num , val From SourceTable

Btw, in the above example, I used Union All , however if you are trying to normalize the data, you might want to have distinct values. In that case, you would use Union instead of Union All .

本文数据库(mssql)相关术语:熊片数据库 mssql数据库 oracle数据库 pubmed数据库 access数据库 万方数据库

代码区博客精选文章
分页:12
转载请注明
本文标题:Insert in 2 tables select the result of a SQL Server table
本站链接:https://www.codesec.net/view/627777.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 数据库(mssql) | 评论(0) | 阅读(358)