在SQL中,是否可以在insert语句中使用虚拟列?

Bil*_*ill 2 sql sql-server-2008

所以我有一些插入:

insert into table (col1, col2, dummy, col3) values (1,1,1,1), (2,2,2,2)
Run Code Online (Sandbox Code Playgroud)

"虚拟"列实际上并不存在,它是必需的,因为我生成了insert语句,甚至是列标题,并且根据情况需要忽略一些列,但是数据仍然是相同的,它会让我的生活成为现实如果我不需要弄乱数据和标题,那就容易多了.

所以我想用另一种方式:是否可以"忽略"插入语句中的列.


换句话说,我试图在包含4列数据的3列上执行insert语句,并且想知道是否有任何方法可以在SQL级别而不是在代码逻辑级别处理此问题.


所以这是一个更长的例子,我有这个2D数组.

{ {101,102,103,104}, {201,202,203,204}, ... }
Run Code Online (Sandbox Code Playgroud)

我有一个包含以下列的表

col1, col2, col3, col4
Run Code Online (Sandbox Code Playgroud)

现在有一个用户说:

"I would like to only use col1, col2, col4"
Run Code Online (Sandbox Code Playgroud)

另一位用户说:

"I would like to only use col2, col3"
Run Code Online (Sandbox Code Playgroud)

如果我不想弄乱2D数据阵列,我该怎么做?

insert into table (col1, col2, ignore, col4) 
    values (101,102,103,104), (201,202,203,204)


insert into table (ignore, col2, col3, ignore) 
    values (101,102,103,104), (201,202,203,204)
Run Code Online (Sandbox Code Playgroud)

请注意,订单很重要.

ype*_*eᵀᴹ 7

这听起来像一个疯狂的疯狂要求,但有一种方法可以使它工作.

使用t包含3列的表(a,b,c),可以使用SQL-Server 2008及更高版本中提供的表值构造函数.请注意如何通过仅更改SQL代码的一行来更改将输入的哪些列插入到表中:

INSERT INTO t 
  (a, b, c) 
SELECT 
  col1, col3, col4            -- this is the only line needs configured
                              -- col2 is ignored
FROM 
  ( VALUES
    ( 1, 2, 3, 4), 
    (11,12,13,14),
    (21,22,23,24),
    (31,21,33,34)
   ) AS x 
     (col1, col2, col3, col4)
;
Run Code Online (Sandbox Code Playgroud)

SQL-Fiddle测试

如果表有4列(a,b,c,d)- 与值列表一样多 - 类似的方法是:

INSERT INTO t 
  (a, b, c, d) 
SELECT 
  col1, NULL, col3, col4         -- this is the only line needs configured
                                 -- col2 is ignored and NULLs are put
                                 -- into column "b"
FROM         --- rest of the code is the same
Run Code Online (Sandbox Code Playgroud)