[英]How to insert data into one table row from multiple table rows in another table in SQL Server 2012?
[英]How to insert one row of a table into two rows of another table
我在表Table1中有一條記錄,我想將該記錄分為兩行並插入到另一表Table2中。
表格1
ID Date User value
1 29/05/18 XXX X_ID||X_value||22||xx
2 29/05/18 YYY Y_ID||Y_value||33|yy
我希望將table1值插入到table2中,作為
表2
P_ID ID Date User Field Value
1 1 29/05/18 XXX X_ID 22
2 1 29/05/18 XXX X_Value XX
3 2 29/05/18 YYY Y_ID 33
4 3 29/05/18 YYY Y_Value YY
來自table1的值是table2中的字段,沒有任何東西可以硬編碼,因為我在表table1中會有很多記錄。 編輯:如果table1中的值具有更多值,例如X_ID || X_VALUE || Y_ID || Y_Value || 22 || xx || 33 || yy,該怎么辦? 我如何使此查詢動態化,以便無論輸出如何將表2中不同行中的記錄分隔開
您可以使用regexp_substr()
:
select id, date, user, regexp_substr(val, '[^|]+', 1, 1) as field, regexp_substr(val, '[^|]+', 1, 3) as value
from table1
union all
select id, date, user, regexp_substr(val, '[^|]+', 1, 2) as field, regexp_substr(val, '[^|]+', 1, 4) as value
from table1;
您可以只使用insert
將其放入另一個表中。 假定p_id
是自動分配的。 如果要自己分配,可以使用row_number()
:
select row_number() over (partition by id order by which) as p_id,
id, date, user, field, value
from ((select id, date, user, regexp_substr(val, '[^|]+', 1, 1) as field, regexp_substr(val, '[^|]+', 1, 3) as value, 1 as which
from table1
) union all
(select id, date, user, regexp_substr(val, '[^|]+', 1, 2) as field, regexp_substr(val, '[^|]+', 1, 4) as value, 2 as which
from table1
)
) t
我試圖通過使用游標來解決問題。
聲明@ID INT
十進制@NAME VARCHAR(50)
宣告@DATE DATE
十進制@VALUE VARCHAR(500)
聲明@List TABLE(項目NVARCHAR(MAX))
聲明@SELECTCURSOR游標
SET @SELECTCURSOR =選擇的光標* FROM tempTable1
打開@SELECTCURSOR
從@SELECTCURSOR進入@ ID,@ DATE,@ NAME,@ VALUE
@@ FETCH_STATUS = 0時
開始
SET @VALUE =替換(@VALUE,'||','。');
插入tempTable2(ID,[User],[Date],Field,Value)VALUES(@ ID,@ NAME,@ DATE,ParseName(@ VALUE,4),PARSENAME(@ VALUE,2))
插入tempTable2(ID,[User],[Date],Field,Value)VALUES(@ ID,@ NAME,@ DATE,ParseName(@ VALUE,3),PARSENAME(@ VALUE,1))
從@SELECTCURSOR進入@ ID,@ DATE,@ NAME,@ VALUE
結束
關閉@SELECTCURSOR
取消分配@SELECTCURSOR
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.