根据条件将行插入表中

时间:2015-07-09 03:39:04

标签: vb.net tsql insert dataset datarow

假设我有5列包含'A'或'B'

的值
+------+------+------+------+------+
| Col1 | Col2 | Col3 | Col4 | Col5 |
+------+------+------+------+------+
| A    | A    | B    | A    | B    |
| B    | A    | B    | B    | A    |
+------+------+------+------+------+

我还想将这5列分配给ID号为1到5

+----+---------+
| ID | Columns |
+----+---------+
|  1 | Col1    |
|  2 | Col2    |
|  3 | Col3    |
|  4 | Col4    |
|  5 | Col5    |
+----+---------+

如果第一行中的col1,col2,col4包含一个' A'那么我想要做的是将新行插入到db表中。在这种情况下,将插入3个新行,每个行包含各自的ID号。

我插入的表应该看起来像这样

 +----+----------+----------+----------+----------+
    | ID | SomeCol0 | SomeCol1 | SomeCol2 | SomeCol3 |
    +----+----------+----------+----------+----------+
    |  1 | x        | x        | x        | x        |
    |  2 | x        | x        | x        | x        |
    |  4 | x        | x        | x        | x        |
    +----+----------+----------+----------+----------+

这适用于VB.NET应用程序。我更喜欢在TSQL中使用这个逻辑,但VB代码也可以。我真的不知所措。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

让我们说我们有以下数据:

DECLARE @DataSource TABLE
(
    [Col1] CHAR(1)
   ,[Col2] CHAR(1)
   ,[Col3] CHAR(1)
   ,[Col4] CHAR(1)
   ,[Col5] CHAR(1)
);

INSERT INTO @DataSource ([Col1], [Col2], [Col3], [Col4], [Col5])
VALUES ('A', 'A', 'B', 'A', 'B')  -- this should be inserted
      ,('B', 'A', 'B', 'B', 'B')
      ,('A', 'A', 'A', 'A', 'B')  -- this should be inserted
      ,('B', 'B', 'B', 'A', 'B');

首先,我们需要按您的标准过滤行:

SELECT *
FROM @DataSource
WHERE [Col1] = 'A' AND [Col2] = 'A' AND [Col4] = 'A';

enter image description here

现在,我们需要UNPIVOT上面的结果,以便为每列分配ID值:

SELECT [ID]
      ,[Value]
FROM
(
    SELECT [Col1] AS [1]
          ,[Col2] AS [2]
          ,[Col3] AS [3]
          ,[Col4] AS [4]
          ,[Col5] AS [5]
    FROM @DataSource
    WHERE [Col1] = 'A' AND [Col2] = 'A' AND [Col4] = 'A' 
) DS
UNPIVOT
(
    [Value] FOR [ID] IN ([1], [2], [3], [4], [5])
) UNPVT;

enter image description here

最后,只需使用WHERE子句按ID过滤:

SELECT [ID]
      ,[Value]
FROM
(
    SELECT [Col1] AS [1]
          ,[Col2] AS [2]
          ,[Col3] AS [3]
          ,[Col4] AS [4]
          ,[Col5] AS [5]
    FROM @DataSource
    WHERE [Col1] = 'A' AND [Col2] = 'A' AND [Col4] = 'A' 
) DS
UNPIVOT
(
    [Value] FOR [ID] IN ([1], [2], [3], [4], [5])
) UNPVT
WHERE [ID] IN (1, 2, 4);

enter image description here