Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

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

$
0
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 .


Viewing all articles
Browse latest Browse all 3160

Trending Articles