SQL Server 插入示例

2022-01-09 00:00:00 sql insert sql-server

我偶尔会在 Oracle 和 SQL Server 之间切换,经常忘记如何在 SQL Server 中完成一些最琐碎的任务.我想使用 SQL 手动将一行数据插入到 SQL Server 数据库表中.最简单的方法是什么?

I switch between Oracle and SQL Server occasionally, and often forget how to do some of the most trivial tasks in SQL Server. I want to manually insert a row of data into a SQL Server database table using SQL. What is the easiest way to do that?

例如,如果我有一个 USERS 表,其中包含 ID(编号)、FIRST_NAME 和 LAST_NAME 列,我应该使用什么查询向该表中插入一行?

For example, if I have a USERS table, with the columns of ID (number), FIRST_NAME, and LAST_NAME, what query do I use to insert a row into that table?

如果我想一次插入多行,我应该使用什么语法?

Also what syntax do I use if I want to insert multiple rows at a time?

推荐答案

插入单行数据:

INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');

要对特定列(而不是所有列)进行插入,您必须指定要更新的列.

To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');

在 SQL Server 2008 或更高版本中插入多行数据:

To insert multiple rows of data in SQL Server 2008 or later:

INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

要在早期版本的 SQL Server 中插入多行数据,请使用UNION ALL",如下所示:

To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'

注意,INTO"关键字在 INSERT 查询中是可选的.可以找到源和更高级的查询 这里.

Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.

相关文章