我有兩個不同表的條目組合,其中一個具有可變數目的條目和填充列的問題。組合兩個臨時表與可變數目的條目
我的輸入數據:
我有一個包含可變數目個條目的表1 /列(我只知道有多少列有可能是最大的),我有一個定義的項目數的表2和我使用定義的列數創建了我的結果的表格(列數=組合前兩個表格的最大列數)。
我的任務是:
我想利用 - 從表1行中所有條目 - 且僅結合起來 - 四項連續從表2 - 在新表3一行。但同時我不知道table1有多少個填充列。所以我不能在table3的哪一列中定義table1的條目應該被插入。
示例數據:
-- TABLE1 and TABLE2 are my input
-- Here I defined 8 columns for TABLE1, but it can be more or less
CREATE TABLE #t1(
[ID] [int] identity(1,1),
[IDBG1] [int] NULL,
[BG1] nvarchar(max),
[IDBG2] [int] NULL,
[BG2] nvarchar(max),
[IDBG3] [int] NULL,
[BG3] nvarchar(max),
[IDBG4] [int] NULL,
[BG4] nvarchar(max)
)
CREATE TABLE #t2(
[ID] [int] identity(1,1),
[IDBG1] [int] NULL,
[BG1] nvarchar(max),
[IDBG2] [int] NULL,
[BG2] nvarchar(max)
)
-- TABLE3 is for my results
-- number of columns is max. number of columns of TABLE 1 plus number of columns of TABLE2
-- here: 8 Columns for TABLE1 entries and 4 columns for TABLE2 entries
CREATE TABLE #t3(
[ID] [int] identity(1,1),
[IDBG1] [int] NULL,
[BG1] nvarchar(max),
[IDBG2] [int] NULL,
[BG2] nvarchar(max),
[IDBG3] [int] NULL,
[BG3] nvarchar(max),
[IDBG4] [int] NULL,
[BG4] nvarchar(max),
[IDBG5] [int] NULL,
[BG5] nvarchar(max),
[IDBG6] [int] NULL,
[BG6] nvarchar(max)
)
-- the IDBG entries are ID's and the BG's are the corresponding names
-- for example
INSERT INTO #t1 (IDBG1, BG1, IDBG2, BG2, IDBG3, BG3, IDBG4, BG4)
VALUES (102, 'BS', 302, 'SL', 345, 'AS', 75, 'LT')
INSERT INTO #t2 (IDBG1, BG1, IDBG2, BG2)
VALUES (900, 'SM', 789, 'CS')
SELECT * FROM #t1
SELECT * FROM #t2
SELECT * FROM #t3
這可能嗎?因爲我只知道,應該填寫的列必須在之前指定!
添加樣本表數據及其預期結果。 – jarlh
聽起來像一個視圖將更合適 – AntDC
我添加了一些示例數據。希望你現在明白更好。 –