gpt4 book ai didi

sql - 在 SQL 中,是否可以在插入语句中使用虚拟列?

转载 作者:行者123 更新时间:2023-12-04 21:39:20 24 4
gpt4 key购买 nike

所以我有一些插入:

insert into table (col1, col2, dummy, col3) values (1,1,1,1), (2,2,2,2)

“虚拟”列实际上并不存在,它是必需的,因为我生成了插入语句,甚至列标题,并且根据情况需要忽略某些列,但数据仍然相同,这将使我的生活变得如果我不需要弄乱数据和标题,那就容易多了。

所以我想换一种说法:是否可以“忽略”插入语句中的列。

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

所以这是一个更长的例子,我有这个二维数组。
{ {101,102,103,104}, {201,202,203,204}, ... }

我有一个包含以下列的表格
col1, col2, col3, col4

现在一位用户说:
"I would like to only use col1, col2, col4"

另一个用户说:
"I would like to only use col2, col3"

如果我不想弄乱二维数据数组,我该怎么做?
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)

请注意,顺序很重要。

最佳答案

这听起来像是一个非常疯狂的要求,但有一种方法可以让它发挥作用。

带表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)
;

测试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

关于sql - 在 SQL 中,是否可以在插入语句中使用虚拟列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21243707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com